<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Models\Traits\BelongsToDealer;
use InvalidArgumentException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, HasRoles, SoftDeletes, BelongsToDealer;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'dealer_id',
        'department_id',
        'branch_id',
        'name',
        'surname',
        'email',
        'phone',
        'password',
        'is_disabled',
        'force_password_change',
        'failed_login_attempts',
        'failed_login_first_at',
        'last_failed_login_at',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
        'is_disabled' => 'bool',
        'force_password_change' => 'bool',
        'is_builtin' => 'bool',
        'failed_login_first_at' => 'datetime',
        'last_failed_login_at' => 'datetime',
    ];

    /**
     * Whether the given plain-text password matches the user's current hashed password.
     */
    public function isSamePassword(string $plainPassword): bool
    {
        return Hash::check($plainPassword, $this->password);
    }

    public function dealer(): BelongsTo
    {
        return $this->belongsTo(Dealer::class);
    }

    public function department(): BelongsTo
    {
        return $this->belongsTo(Department::class);
    }

    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class);
    }

    public function hasSystemAdminRole(): bool
    {
        $tableNames = config('permission.table_names');

        return DB::table($tableNames['model_has_roles'].' as mhr')
            ->join($tableNames['roles'].' as roles', 'roles.id', '=', 'mhr.role_id')
            ->where('mhr.model_type', self::class)
            ->where('mhr.model_id', $this->getKey())
            ->where('roles.name', 'System Admin')
            ->exists();
    }

    public function canViewAllBranches(): bool
    {
        if ($this->hasSystemAdminRole()) {
            return true;
        }

        $dealerWideRoles = (array) config('mtt_branch_visibility.dealer_wide_roles', []);

        return $this->hasAnyRole($dealerWideRoles);
    }

    public function setDepartmentIdAttribute($value): void
    {
        if ($value === null || $value === '') {
            $this->attributes['department_id'] = null;

            return;
        }

        // Look up without global scope so assignment works during provisioning (when current dealer context may differ).
        $department = Department::withoutGlobalScopes()->find($value);
        if (!$department) {
            throw new InvalidArgumentException('Invalid department.');
        }

        if (!empty($this->dealer_id) && (int) $department->dealer_id !== (int) $this->dealer_id) {
            throw new InvalidArgumentException('Department must belong to the same dealer.');
        }

        $this->attributes['department_id'] = (int) $value;
    }

    public function setBranchIdAttribute($value): void
    {
        if ($value === null || $value === '') {
            $this->attributes['branch_id'] = null;

            return;
        }

        // Look up without global scope so assignment works even when dealer context differs (e.g. provisioning).
        $branch = Branch::withoutGlobalScopes()->find($value);
        if (! $branch) {
            throw new InvalidArgumentException('Invalid branch.');
        }

        if (! empty($this->dealer_id) && (int) $branch->dealer_id !== (int) $this->dealer_id) {
            throw new InvalidArgumentException('Branch must belong to the same dealer.');
        }

        $this->attributes['branch_id'] = (int) $value;
    }

    public function getFullNameAttribute(): string
    {
        $parts = array_filter([$this->name, $this->surname]);

        return trim(implode(' ', $parts));
    }

    public function getPrimaryRoleNameAttribute(): ?string
    {
        $roles = $this->roles;

        if ($roles->isEmpty()) {
            return null;
        }

        if ($roles->count() === 1) {
            return $roles->first()->name;
        }

        return 'Multiple Roles';
    }
}
