<?php

namespace App\Models;

use App\Enums\EarnMemberStatus;
use App\Notifications\EarnVerifyEmail;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Str;
use Laravel\Sanctum\HasApiTokens;

#[Fillable(['name', 'email', 'password', 'status', 'email_verified_at', 'last_login_at', 'last_login_ip'])]
#[Hidden(['password', 'remember_token'])]
class EarnMember extends Authenticatable implements MustVerifyEmail
{
    use HasApiTokens, HasFactory, Notifiable, SoftDeletes;

    protected static function booted(): void
    {
        static::creating(function (self $member): void {
            $member->ulid ??= (string) Str::ulid();
        });
    }

    protected function casts(): array
    {
        return [
            'password' => 'hashed',
            'status' => EarnMemberStatus::class,
            'email_verified_at' => 'datetime',
            'last_login_at' => 'datetime',
        ];
    }

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

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

    public function canUseApi(): bool
    {
        return ! $this->trashed() && $this->status === EarnMemberStatus::Active && $this->hasVerifiedEmail();
    }

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