<?php

namespace App\Models;

use App\Enums\IsActive;
use App\Enums\RoleEnum;
use App\Enums\VerificationStatus;
use Filament\Models\Contracts\FilamentUser;
use Filament\Panel;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
use Swindon\FilamentHashids\Traits\HasHashid;

class User extends Authenticatable implements FilamentUser, MustVerifyEmail
{
    use HasFactory, HasHashid, HasRoles, Notifiable, SoftDeletes;

    protected $guarded = ['id'];

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

    protected function casts(): array
    {
        return [
            'password' => 'hashed',
            'is_active' => IsActive::class,
            'email_verified_at' => 'timestamp',
        ];
    }

    #[Scope]
    protected function withoutDeveloper(Builder $query): void
    {
        $query->whereDoesntHave('roles', function ($q) {
            $q->where('name', RoleEnum::DEVELOPER);
        });
    }

    #[Scope]
    protected function active(Builder $query): void
    {
        $query->where('is_active', IsActive::ACTIVE);
    }

    #[Scope]
    protected function superAdmin(Builder $query): void
    {
        $query->whereHas('roles', function ($q) {
            $q->whereIn('name', [RoleEnum::DEVELOPER, RoleEnum::ADMINISTRATOR]);
        });
    }

    public function canAccessPanel(Panel $panel): bool
    {
        if ($this->company?->verificationRequest?->status === VerificationStatus::REJECTED) {
            return false;
        }

        return $this->is_active === IsActive::ACTIVE;
    }

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

    public function contacts(): HasMany
    {
        return $this->hasMany(Contact::class, 'replied_by');
    }

    public function dataChangeRequests(): HasMany
    {
        return $this->hasMany(DataChangeRequest::class);
    }

    public function dataChangeReviews(): HasMany
    {
        return $this->hasMany(DataChangeReview::class, 'reviewer_id');
    }

    public function news(): HasMany
    {
        return $this->hasMany(News::class, 'author_id');
    }

    public function verificationRequests(): HasMany
    {
        return $this->hasMany(VerificationRequest::class, 'submitted_by');
    }

    public function verificationReviews(): HasMany
    {
        return $this->hasMany(VerificationReview::class, 'reviewer_id');
    }

    public function visitors(): HasMany
    {
        return $this->hasMany(Visitor::class);
    }
}
