<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class OtpCode extends Model
{
    public $timestamps = false;

    protected $fillable = [
        'user_id', 'email', 'phone', 'code', 'type', 'expires_at', 'verified', 'ip_address',
    ];

    protected $casts = [
        'verified'   => 'boolean',
        'expires_at' => 'datetime',
        'created_at' => 'datetime',
    ];

    const UPDATED_AT = null;

    // ── Relationships ──────────────────────────────────────────────────────────
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    // ── Scopes ────────────────────────────────────────────────────────────────
    public function scopeActive($query)
    {
        return $query->where('verified', false)->where('expires_at', '>', now());
    }

    public function scopeExpired($query)
    {
        return $query->where('verified', false)->where('expires_at', '<=', now());
    }

    public function scopeUsed($query)
    {
        return $query->where('verified', true);
    }

    // ── Helpers ────────────────────────────────────────────────────────────────
    public function getStatusAttribute(): string
    {
        if ($this->verified) return 'used';
        if ($this->expires_at && $this->expires_at->isPast()) return 'expired';
        return 'active';
    }

    public function getStatusLabelAttribute(): string
    {
        return match ($this->status) {
            'active'  => 'فعال',
            'expired' => 'منقضی',
            'used'    => 'استفاده شده',
            default   => '—',
        };
    }

    public function getTypeLabelAttribute(): string
    {
        return match ($this->type) {
            'register'       => 'ثبت‌نام',
            'login'          => 'ورود',
            'reset_password' => 'بازیابی رمز',
            'verify_email'   => 'تایید ایمیل',
            'verify_phone'   => 'تایید شماره',
            default          => $this->type,
        };
    }

    public function getContactAttribute(): string
    {
        return $this->phone ?: ($this->email ?: '—');
    }
}
