<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class KeywordMetricsCache extends Model
{
    use HasFactory;

    public $timestamps = false;

    protected $table = 'keyword_metrics_cache';

    protected $fillable = [
        'keyword_hash',
        'keyword',
        'location_code',
        'search_volume',
        'competition',
        'competition_index',
        'cpc',
        'fetched_at',
        'expires_at',
    ];

    protected $casts = [
        'cpc' => 'decimal:2',
        'fetched_at' => 'datetime',
        'expires_at' => 'datetime',
    ];

    public static function getCachedMetrics(string $keyword, int $locationCode = 2840): ?array
    {
        $keywordHash = md5($keyword . $locationCode);

        $cached = self::where('keyword_hash', $keywordHash)
            ->where('location_code', $locationCode)
            ->where('expires_at', '>', now())
            ->first();

        if (!$cached) {
            return null;
        }

        return [
            'search_volume' => $cached->search_volume,
            'competition' => $cached->competition,
            'competition_index' => $cached->competition_index,
            'cpc' => $cached->cpc,
        ];
    }

    public static function cacheMetrics(string $keyword, array $metrics, int $locationCode = 2840, int $cacheDays = 7): void
    {
        $keywordHash = md5($keyword . $locationCode);

        self::updateOrCreate(
            [
                'keyword_hash' => $keywordHash,
                'location_code' => $locationCode,
            ],
            [
                'keyword' => $keyword,
                'search_volume' => $metrics['search_volume'] ?? 0,
                'competition' => $metrics['competition'] ?? null,
                'competition_index' => $metrics['competition_index'] ?? null,
                'cpc' => $metrics['cpc'] ?? null,
                'fetched_at' => now(),
                'expires_at' => now()->addDays($cacheDays),
            ]
        );
    }

    public static function clearExpired(): int
    {
        return self::where('expires_at', '<', now())->delete();
    }
}
