<?php

namespace KeyLair;

use PDOException;

class KeyImporter
{
    /**
     * @param string[] $rawLines One key per line, as pasted or read from a CSV/TXT file.
     * @param string $pool 'active' (immediately claimable) or 'inactive' (held back until
     *   an admin releases it — see admin/keys_pool.php).
     * @return array{imported: int, skipped_duplicate: int, skipped_blank: int, skipped_invalid_format: int, duplicate_values: string[], invalid_format_values: string[]}
     */
    public static function import(int $productId, ?int $campaignId, string $platform, array $rawLines, string $pool = 'inactive'): array
    {
        if (!Platform::exists($platform)) {
            throw new \InvalidArgumentException('Invalid platform: ' . $platform);
        }
        if (!in_array($pool, ['active', 'inactive'], true)) {
            throw new \InvalidArgumentException('Invalid pool: ' . $pool);
        }

        $pdo = Database::connection();
        $stmt = $pdo->prepare(
            'INSERT INTO `keys` (product_id, campaign_id, platform, key_value, status, pool, created_at)
             VALUES (:product_id, :campaign_id, :platform, :key_value, "available", :pool, NOW())'
        );

        $imported = 0;
        $duplicates = 0;
        $blank = 0;
        $invalidFormat = 0;
        $duplicateValues = [];
        $invalidFormatValues = [];

        // Dedupe within the pasted batch itself too, not just against the DB.
        $seenInBatch = [];

        foreach ($rawLines as $line) {
            // Allow simple CSV with one column, or the first column if multiple were pasted.
            $value = trim(explode(',', trim($line))[0]);
            $value = trim($value, "\"' \t\n\r");

            if ($value === '') {
                $blank++;
                continue;
            }

            if (!Platform::matchesKeyFormat($platform, $value)) {
                $invalidFormat++;
                $invalidFormatValues[] = $value;
                continue;
            }

            if (isset($seenInBatch[$value])) {
                $duplicates++;
                $duplicateValues[] = $value;
                continue;
            }
            $seenInBatch[$value] = true;

            try {
                $stmt->execute([
                    'product_id' => $productId,
                    'campaign_id' => $campaignId,
                    'platform' => $platform,
                    'key_value' => $value,
                    'pool' => $pool,
                ]);
                $imported++;
            } catch (PDOException $e) {
                // Unique constraint (product_id, platform, key_value) — already exists in the DB.
                if ((int) $e->errorInfo[1] === 1062) {
                    $duplicates++;
                    $duplicateValues[] = $value;
                } else {
                    throw $e;
                }
            }
        }

        return [
            'imported' => $imported,
            'skipped_duplicate' => $duplicates,
            'skipped_blank' => $blank,
            'skipped_invalid_format' => $invalidFormat,
            'duplicate_values' => $duplicateValues,
            'invalid_format_values' => $invalidFormatValues,
        ];
    }
}
