<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Support\Facades\DB;

class UUID extends Model
{
    use HasUuids;

    protected $table = 'tb_uuid';
    protected $primaryKey = 'id';

    public $keyType = 'int';
    public $incrementing = true;
    public $timestamps = true;

    const CREATED_AT = 'created_at';
    const UPDATED_AT = null;
    const DELETED_AT = null;

    protected $guarded = [];

    /**
     * Target ID 에 해당하는 멱등키가 있는지 확인
     * 만료시간 이내의 멱등키를 조회한다.
     */
    public function isExistsTargetID(string $targetID): bool
    {
        $sql = '
            SELECT COUNT(*) AS `exists` FROM tb_uuid WHERE target_id = ? AND expiry_time > UNIX_TIMESTAMP() LIMIT 1;
        ';

        return DB::selectOne($sql, [$targetID])->exists;
    }

    /**
     * 주문번호(Target ID)에 해당하는 멱등키가 있는지 확인
     * 만료시간 이내의 멱등키를 조회한다.
     */
    public function findTargetIDKey(string $targetID): ?string
    {
        $sql = '
            SELECT idempotency_key FROM tb_uuid WHERE target_id = ? AND expiry_time > UNIX_TIMESTAMP() LIMIT 1;
        ';

        return DB::selectOne($sql, [$targetID])?->idempotency_key;
    }

    /**
     * 멱등키 새로 생성
     */
    public function newUUID(string $targetID, int $expiryTime): string
    {
        $uuid = $this->newUniqueId();

        $this->insert([
            'target_id' => $targetID,
            'idempotency_key' => $uuid,
            'expiry_time' => $expiryTime,
            'created_at' => now()
        ]);

        return $uuid;
    }
}
