<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class EmailOtp extends Model
{
    protected $fillable = ['email', 'otp', 'type', 'expires_at', 'used_at'];

    protected function casts(): array
    {
        return [
            'expires_at' => 'datetime',
            'used_at'    => 'datetime',
        ];
    }

    public function isExpired(): bool
    {
        return $this->expires_at->isPast();
    }

    public function isUsed(): bool
    {
        return $this->used_at !== null;
    }

    // Generate a new 6-digit OTP and invalidate any previous ones for the same email+type
    public static function generate(string $email, string $type): self
    {
        // Invalidate all previous unused OTPs for this email and type
        static::where('email', $email)
            ->where('type', $type)
            ->whereNull('used_at')
            ->delete();

        $minutes = $type === 'email_verification' ? 10 : 15;

        return static::create([
            'email'      => $email,
            'otp'        => str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT),
            'type'       => $type,
            'expires_at' => now()->addMinutes($minutes),
        ]);
    }

    // Find a valid (unused, unexpired) OTP
    public static function findValid(string $email, string $otp, string $type): ?self
    {
        return static::where('email', $email)
            ->where('otp', $otp)
            ->where('type', $type)
            ->whereNull('used_at')
            ->where('expires_at', '>', now())
            ->latest()
            ->first();
    }

    public function markUsed(): void
    {
        $this->update(['used_at' => now()]);
    }
}
