<?php

declare(strict_types=1);

namespace ImovelZapAi\Users\Infrastructure\Persistence\Eloquent;

use Database\Factories\UserFactory;
use Illuminate\Auth\MustVerifyEmail as MustVerifyEmailTrait;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use ImovelZapAi\Authentication\Infrastructure\Notifications\ResetPasswordNotification;
use ImovelZapAi\Authentication\Infrastructure\Notifications\VerifyEmailNotification;
use ImovelZapAi\Shared\Infrastructure\Persistence\Concerns\BelongsToTenant;
use ImovelZapAi\Users\Domain\Entities\User as UserEntity;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;

class UserModel extends Authenticatable implements MustVerifyEmail
{
    use BelongsToTenant;
    use HasApiTokens;
    use HasRoles;

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

    protected $table = 'users';

    /** @var list<string> */
    protected $fillable = [
        'tenant_id',
        'name',
        'email',
        'phone',
        'creci',
        'password',
        'email_verified_at',
    ];

    /** @var list<string> */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /** @return array<string, string> */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    public function toDomainEntity(): UserEntity
    {
        return new UserEntity(
            id: $this->getKey(),
            tenantId: (string) $this->tenant_id,
            name: $this->name,
            email: $this->email,
        );
    }

    protected static function newFactory(): UserFactory
    {
        return UserFactory::new();
    }

    public function sendPasswordResetNotification(#[\SensitiveParameter] $token): void
    {
        $this->notify(new ResetPasswordNotification($token));
    }

    public function sendEmailVerificationNotification(): void
    {
        $this->notify(new VerifyEmailNotification);
    }
}
