<?php

/**
 * JCOGS Image Pro - LicenseRuntimeRepository
 * ==========================================
 * Persists CP license runtime state in shared governance table.
 *
 * @category   ExpressionEngine Add-on
 * @package    JCOGS Image Pro
 * @author     JCOGS Design <contact@jcogs.net>
 * @copyright  Copyright (c) 2021 - 2026 JCOGS Design
 * @license    https://jcogs.net/add-ons/license/jcogs_img_pro
 * @version    2.0.6
 * @link       https://jcogs.net/
 * @since      2.0.0
 */

namespace JCOGSDesign\JCOGSImagePro\Service\License;

class LicenseRuntimeRepository implements LicenseRuntimeRepositoryInterface
{
    private const TABLE = 'jcogs_pro_license_runtime';

    public function ensureSchema(): void
    {
        // Schema ownership is migration-based. This method is intentionally lightweight.
    }

    public function findForAddon(int $siteId, string $addonShortName): ?array
    {
        $row = ee()->db->select('*')
            ->from(self::TABLE)
            ->where('site_id', $siteId)
            ->where('addon_short_name', $addonShortName)
            ->get()
            ->row_array();

        return $row ?: null;
    }

    public function seedIfMissing(int $siteId, string $addonShortName, int $now): void
    {
        if ($this->findForAddon($siteId, $addonShortName) !== null) {
            return;
        }

        ee()->db->insert(self::TABLE, [
            'site_id' => $siteId,
            'addon_short_name' => $addonShortName,
            'first_seen_at' => $now,
            'first_restricted_at' => null,
            'last_known_status' => 'na',
            'status_checked_at' => $now,
            'grace_ends_at' => null,
            'created_at' => $now,
            'updated_at' => $now,
        ]);
    }

    public function updateStatus(
        int $siteId,
        string $addonShortName,
        string $status,
        int $checkedAt,
        ?int $graceEndsAt,
        ?int $firstRestrictedAt = null
    ): void {
        $this->seedIfMissing($siteId, $addonShortName, $checkedAt);

        $update = [
            'last_known_status' => $status,
            'status_checked_at' => $checkedAt,
            'grace_ends_at' => $graceEndsAt,
            'updated_at' => $checkedAt,
        ];

        if ($firstRestrictedAt !== null) {
            $update['first_restricted_at'] = $firstRestrictedAt;
        }

        ee()->db->where('site_id', $siteId)
            ->where('addon_short_name', $addonShortName)
            ->update(self::TABLE, $update);
    }
}
