<?php

namespace App\Models;

use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\HR\Employees\Models\Employee;
use App\Modules\Settings\Rbac\Models\Role;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

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

    protected $fillable = [
        'name',
        'email',
        'password',
        'tenant_id',
        'employee_id',
        'is_admin',
        'is_active',
        'deactivated_at',
        'invitation_token',
        'invitation_expires_at',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'is_admin' => 'boolean',
            'is_tenant_owner' => 'boolean',
            'is_active' => 'boolean',
            'deactivated_at' => 'datetime',
            'invitation_expires_at' => 'datetime',
        ];
    }

    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class, 'user_roles');
    }

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

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

    public function isAdmin(): bool
    {
        return (bool) $this->is_admin;
    }

    /**
     * Designated tenant owner: full tenant ability checks without role slug matching.
     * Still tenant-scoped (no cross-tenant access via permission arguments).
     */
    public function isTenantOwner(): bool
    {
        return (bool) $this->is_tenant_owner && $this->tenant_id !== null;
    }
}
