<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use App\Support\TenantPermissionCatalog;

class User extends Authenticatable
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'tenant_id',
        'branch_id',
        'role',
        'role_profile_id',
        'name',
        'email',
        'phone',
        'password',
        'status',
        'last_login_at',
    ];

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

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'last_login_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    public const ROLE_SUPER_ADMIN = 'super_admin';
    public const ROLE_TENANT_ADMIN = 'tenant_admin';
    public const ROLE_MANAGER = 'manager';
    public const ROLE_LOAN_OFFICER = 'loan_officer';
    public const ROLE_ACCOUNTANT = 'accountant';
    public const ROLE_CUSTOMER = 'customer';
    public const ROLE_AGENT = 'agent';

    public const ROLES = [
        self::ROLE_SUPER_ADMIN => 'Super Admin',
        self::ROLE_TENANT_ADMIN => 'Tenant Admin',
        self::ROLE_MANAGER => 'Manager',
        self::ROLE_LOAN_OFFICER => 'Loan Officer',
        self::ROLE_ACCOUNTANT => 'Accountant',
        self::ROLE_CUSTOMER => 'Member',
        self::ROLE_AGENT => 'Merchant',
    ];

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

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

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

    public function assignedCustomers(): HasMany
    {
        return $this->hasMany(Customer::class, 'account_officer_id');
    }

    public function agent(): HasOne
    {
        return $this->hasOne(Agent::class);
    }

    public function wallet(): HasOne
    {
        return $this->hasOne(UserWallet::class);
    }

    public function isSuperAdmin(): bool
    {
        return $this->role === self::ROLE_SUPER_ADMIN;
    }

    public function isTenantAdmin(): bool
    {
        return $this->role === self::ROLE_TENANT_ADMIN;
    }

    public function isAgent(): bool
    {
        return $this->role === self::ROLE_AGENT;
    }

    public function canViewAllTenantCustomers(): bool
    {
        return $this->isSuperAdmin() || $this->isTenantAdmin();
    }

    public function isTenantUser(): bool
    {
        return ! $this->isSuperAdmin() && $this->tenant_id !== null;
    }

    public function hasAnyRole(array $roles): bool
    {
        return in_array($this->role, $roles, true);
    }

    public function hasPermission(string $permission): bool
    {
        if ($this->isSuperAdmin() || $this->role === self::ROLE_TENANT_ADMIN) {
            return true;
        }

        if ($this->role === self::ROLE_CUSTOMER) {
            return false;
        }

        if ($this->roleProfile) {
            return $this->roleProfile->hasPermission($permission);
        }

        return in_array($permission, TenantPermissionCatalog::defaultForRole($this->role), true);
    }

    public function roleLabel(): string
    {
        return self::ROLES[$this->role] ?? ucfirst(str_replace('_', ' ', (string) $this->role));
    }
}
