<?php

declare(strict_types=1);

/**
 * @deprecated APO-170 retires direct footer override writes. Use MyronTemplateChromeAssignmentRepository.
 */
final class MyronFooterVariantOverrideRepository
{
    private const DEFAULTS = [
        'footer_variant' => 'inherit',
    ];

    private const OPTIONS = [
        'footer_variant' => [
            'inherit',
            'footer.standard',
            'footer.portfolio',
            'footer.editorial',
            'footer.mega',
            'footer.ecom',
            'footer.local-business',
            'footer.conversion',
            'footer.creator',
            'footer.campaign',
            'footer.checkout',
        ],
    ];

    private const SCOPE_TYPES = ['page', 'template'];

    public function __construct(private readonly PDO $pdo)
    {
    }

    /**
     * @return array<string, list<string>>
     */
    public function optionSets(): array
    {
        return self::OPTIONS;
    }

    /**
     * @return array<string, string>
     */
    public function defaults(): array
    {
        return self::DEFAULTS;
    }

    /**
     * @return list<array<string, mixed>>
     */
    public function listOverrides(?string $scopeType = null): array
    {
        $sql = 'SELECT * FROM footer_variant_overrides';
        $params = [];
        if ($scopeType !== null && trim($scopeType) !== '') {
            $sql .= ' WHERE scope_type = :scope_type';
            $params[':scope_type'] = $this->normalizeScopeType($scopeType);
        }
        $sql .= ' ORDER BY scope_type ASC, scope_key ASC';

        $statement = $this->pdo->prepare($sql);
        $statement->execute($params);

        $overrides = [];
        foreach ($statement->fetchAll(PDO::FETCH_ASSOC) as $row) {
            if (is_array($row)) {
                $overrides[] = $this->hydrate($row);
            }
        }

        return $overrides;
    }

    /**
     * @return array<string, mixed>|null
     */
    public function findOverride(string $scopeType, string $scopeKey): ?array
    {
        $normalizedType = $this->normalizeScopeType($scopeType);
        $normalizedKey  = $this->normalizeScopeKey($normalizedType, $scopeKey);
        if ($normalizedKey === '') {
            return null;
        }

        $statement = $this->pdo->prepare(
            'SELECT * FROM footer_variant_overrides
             WHERE scope_type = :scope_type AND scope_key = :scope_key
             LIMIT 1'
        );
        $statement->execute([':scope_type' => $normalizedType, ':scope_key' => $normalizedKey]);
        $row = $statement->fetch(PDO::FETCH_ASSOC);

        return is_array($row) ? $this->hydrate($row) : null;
    }

    public function saveOverride(
        string $scopeType,
        string $scopeKey,
        string $footerVariant,
        string $updatedByUserId
    ): void {
        $normalizedType    = $this->normalizeScopeType($scopeType);
        $normalizedKey     = $this->normalizeScopeKey($normalizedType, $scopeKey);
        $normalizedVariant = $this->normalizeVariant($footerVariant);

        if ($normalizedKey === '') {
            throw new RuntimeException('Invalid scope key for footer variant override.');
        }

        $now = myronNow();
        $id  = myronGenerateId('fvo');

        $existing = $this->findOverride($normalizedType, $normalizedKey);

        if ($existing !== null) {
            $update = $this->pdo->prepare(
                'UPDATE footer_variant_overrides
                 SET footer_variant = :footer_variant,
                     updated_by_user_id = :updated_by_user_id,
                     updated_at = :updated_at
                 WHERE scope_type = :scope_type AND scope_key = :scope_key'
            );
            $update->execute([
                ':footer_variant'     => $normalizedVariant,
                ':updated_by_user_id' => $updatedByUserId,
                ':updated_at'         => $now,
                ':scope_type'         => $normalizedType,
                ':scope_key'          => $normalizedKey,
            ]);
        } else {
            $insert = $this->pdo->prepare(
                'INSERT INTO footer_variant_overrides
                    (id, scope_type, scope_key, footer_variant, updated_by_user_id, created_at, updated_at)
                 VALUES (:id, :scope_type, :scope_key, :footer_variant, :updated_by_user_id, :created_at, :updated_at)'
            );
            $insert->execute([
                ':id'                  => $id,
                ':scope_type'          => $normalizedType,
                ':scope_key'           => $normalizedKey,
                ':footer_variant'      => $normalizedVariant,
                ':updated_by_user_id'  => $updatedByUserId,
                ':created_at'          => $now,
                ':updated_at'          => $now,
            ]);
        }
    }

    public function deleteOverride(string $scopeType, string $scopeKey): void
    {
        $normalizedType = $this->normalizeScopeType($scopeType);
        $normalizedKey  = $this->normalizeScopeKey($normalizedType, $scopeKey);

        if ($normalizedKey === '') {
            return;
        }

        $statement = $this->pdo->prepare(
            'DELETE FROM footer_variant_overrides WHERE scope_type = :scope_type AND scope_key = :scope_key'
        );
        $statement->execute([':scope_type' => $normalizedType, ':scope_key' => $normalizedKey]);
    }

    private function normalizeScopeType(string $scopeType): string
    {
        $trimmed = trim(strtolower($scopeType));
        return in_array($trimmed, self::SCOPE_TYPES, true) ? $trimmed : 'template';
    }

    private function normalizeScopeKey(string $scopeType, string $scopeKey): string
    {
        $trimmed = trim($scopeKey);
        if ($trimmed === '') {
            return '';
        }
        return $scopeType === 'page' ? myronNormalizePath($trimmed) : $trimmed;
    }

    private function normalizeVariant(string $variant): string
    {
        $trimmed = trim($variant);
        return in_array($trimmed, self::OPTIONS['footer_variant'], true) ? $trimmed : 'inherit';
    }

    /**
     * @param array<string, mixed> $row
     * @return array<string, mixed>
     */
    private function hydrate(array $row): array
    {
        return [
            'id'                 => (string) ($row['id'] ?? ''),
            'scope_type'         => (string) ($row['scope_type'] ?? ''),
            'scope_key'          => (string) ($row['scope_key'] ?? ''),
            'footer_variant'     => (string) ($row['footer_variant'] ?? 'inherit'),
            'updated_by_user_id' => (string) ($row['updated_by_user_id'] ?? ''),
            'created_at'         => (string) ($row['created_at'] ?? ''),
            'updated_at'         => (string) ($row['updated_at'] ?? ''),
        ];
    }
}
