<?php

namespace App\Auth;

use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

class PortalAuthenticator
{
    /**
     * Match a management account and return the local user that owns app data.
     *
     * @throws ValidationException
     */
    public function authenticate(string $identity, string $password): User
    {
        $identity = trim($identity);
        $portalUser = $this->findPortalUser($identity, $password);

        if ($portalUser === null) {
            throw ValidationException::withMessages([
                'form.identity' => trans('auth.failed'),
            ]);
        }

        if (! $this->hasPortalAccess($portalUser)) {
            throw ValidationException::withMessages([
                'form.identity' => 'You do not have permission to access this portal. Contact an admin.',
            ]);
        }

        return $this->localUser($portalUser);
    }

    private function findPortalUser(string $identity, string $password): ?object
    {
        if ($identity === '' || $password === '') {
            return null;
        }

        return DB::connection('admin')
            ->table('portal_users')
            ->where('status', 1)
            ->where('password', md5($password))
            ->where(function ($query) use ($identity) {
                $query->where('username', $identity)->orWhere('email', $identity);
            })
            ->first();
    }

    private function hasPortalAccess(object $portalUser): bool
    {
        if ((int) $portalUser->is_superuser === 1) {
            return true;
        }

        $portalId = (int) config('portal.id');

        return DB::connection('admin')
            ->table('portal_users_permissions as pup')
            ->join('portal_pages as pp', function ($join) {
                $join->on('pp.page_id', '=', 'pup.page_id')->where('pp.status', 1);
            })
            ->where('pup.user_id', $portalUser->user_id)
            ->where('pup.status', 1)
            ->where('pp.portal_id', $portalId)
            ->exists();
    }

    private function localUser(object $portalUser): User
    {
        $email = trim((string) $portalUser->email);
        if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
            throw ValidationException::withMessages([
                'form.identity' => 'This account has no email address. Contact an admin.',
            ]);
        }

        $name = trim(((string) $portalUser->first_name).' '.((string) $portalUser->last_name));
        if ($name === '') {
            $name = (string) $portalUser->username;
        }

        $user = User::query()->where('portal_user_id', $portalUser->user_id)->first()
            ?? User::query()->where('email', $email)->first();

        if ($user !== null && $user->portal_user_id !== null && (int) $user->portal_user_id !== (int) $portalUser->user_id) {
            throw ValidationException::withMessages([
                'form.identity' => 'This email is already linked to a different account.',
            ]);
        }

        if ($user !== null && User::query()->where('email', $email)->whereKeyNot($user->getKey())->exists()) {
            throw ValidationException::withMessages([
                'form.identity' => 'This email is already linked to a different account.',
            ]);
        }

        if ($user !== null) {
            $user->forceFill([
                'name' => $name,
                'email' => $email,
                'portal_user_id' => $portalUser->user_id,
                'email_verified_at' => $user->email_verified_at ?? now(),
            ])->save();

            return $user;
        }

        return User::query()->forceCreate([
            'name' => $name,
            'email' => $email,
            'password' => Str::random(40),
            'portal_user_id' => $portalUser->user_id,
            'email_verified_at' => now(),
        ]);
    }
}
