<?php

namespace App\Models;

use App\Enums\UserAccessLevel;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

// use App\Traits\Auditable;

class User extends Authenticatable
{
    use HasApiTokens;

    /** @use HasFactory<UserFactory> */
    use HasFactory, Notifiable;

    use SoftDeletes;
    // use Audittable;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'username',
        'email',
        'whatsapp_number',
        'profile_photo_file_id',
        'password',
        'is_master',
        'is_platform_staff',
        'access_level',
        'status',
        'verification_channel',
        'verification_target',
        'verification_code',
        'verification_code_expires_at',
        'verified_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',
            'password' => 'hashed',
            'is_master' => 'boolean',
            'is_platform_staff' => 'boolean',
            'access_level' => UserAccessLevel::class,
            'verification_code_expires_at' => 'datetime',
            'verified_at' => 'datetime',
        ];
    }

    public function menuGroups()
    {
        return $this->belongsToMany(
            MenuGroup::class,
            'user_menu_groups',
            'user_id',
            'menu_group_id'
        )->withPivot(['tenant_id'])->withTimestamps();
    }

    public function userProfile()
    {
        return $this->hasOne(UserProfile::class, 'user_id');
    }

    public function profilePhoto()
    {
        return $this->belongsTo(StoredFile::class, 'profile_photo_file_id');
    }

    public function userTenants()
    {
        return $this->hasMany(UserTenant::class, 'user_id');
    }

    public function userMenuGroups()
    {
        return $this->hasMany(UserMenuGroup::class, 'user_id');
    }

    public function userNotifications()
    {
        return $this->hasMany(UserNotification::class, 'user_id');
    }

    public function wallets()
    {
        return $this->morphMany(Wallet::class, 'owner');
    }

    public function voucherAgents()
    {
        return $this->hasMany(VoucherAgent::class);
    }

    public function roleApplications()
    {
        return $this->hasMany(RoleApplication::class, 'applicant_user_id');
    }

    public function linkedCustomers()
    {
        return $this->belongsToMany(Customer::class, 'customer_user_links')->withPivot(['tenant_id', 'relationship', 'is_primary'])->withTimestamps();
    }

    public function isMasterAdmin(): bool
    {
        return $this->is_master || $this->access_level === UserAccessLevel::MASTER_ADMIN;
    }

    public function isTenantOwner(?int $tenantId = null): bool
    {
        if ($this->access_level !== UserAccessLevel::TENANT_OWNER) {
            return false;
        }

        return $this->userTenants()
            ->where('role', 'tenant_owner')
            ->when($tenantId, fn ($query) => $query->where('tenant_id', $tenantId))
            ->exists();
    }

    public function tenantRole(?int $tenantId): ?string
    {
        if (! $tenantId) {
            return null;
        }

        return $this->userTenants()->where('tenant_id', $tenantId)->value('role');
    }
}

// {
//   "email": "master@services-core.local",
//   "password": "Master@12345"
// }
