<?php

declare(strict_types=1);

require __DIR__ . '/dev-db.php';
require __DIR__ . '/golden-master-data.php';

$pdo = dev_pdo();
dev_apply_schema($pdo);

$dates = gm_dates();
$members = gm_members();
$payments = gm_payments();
$consumptions = gm_consumptions();

$emails = array_values(array_map(static fn (array $member): string => $member['email'], $members));
$placeholders = implode(',', array_fill(0, count($emails), '?'));

$pdo->beginTransaction();

try {
    $step = 'select existing fixture ids';
    $stmt = $pdo->prepare("SELECT MitarbeiterID FROM kl_Mitarbeiter WHERE Email IN ({$placeholders})");
    $stmt->execute($emails);
    $ids = array_map('intval', $stmt->fetchAll(PDO::FETCH_COLUMN));

    if ($ids !== []) {
        $idPlaceholders = implode(',', array_fill(0, count($ids), '?'));
        $step = 'delete fixture payments';
        $stmt = $pdo->prepare("DELETE FROM kl_Einzahlungen WHERE MitarbeiterID IN ({$idPlaceholders})");
        $stmt->execute($ids);
        $step = 'delete fixture consumption';
        $stmt = $pdo->prepare("DELETE FROM kl_Kaffeeverbrauch WHERE MitarbeiterID IN ({$idPlaceholders})");
        $stmt->execute($ids);
    }

    $step = 'delete fixture members';
    $stmt = $pdo->prepare("DELETE FROM kl_Mitarbeiter WHERE Email IN ({$placeholders})");
    $stmt->execute($emails);

    $step = 'delete fixture notices';
    $pdo->exec("DELETE FROM kl_hinweise WHERE nachricht LIKE '[GM]%'");
    $step = 'delete fixture survey locks';
    $pdo->exec("DELETE FROM CoffeeSurveyVotedEmails WHERE EmailNorm LIKE 'gm-%@test.local'");

    $insertMember = $pdo->prepare(
        'INSERT INTO kl_Mitarbeiter (Name, Email, paypalname, aktiv, admin)
         VALUES (?, ?, ?, ?, ?)'
    );
    $selectMemberId = $pdo->prepare('SELECT MitarbeiterID FROM kl_Mitarbeiter WHERE Email = ?');
    $memberIds = [];

    foreach ($members as $key => $member) {
        $step = 'insert member ' . $key;
        $insertMember->execute([
            $member['name'],
            $member['email'],
            $member['paypalname'],
            $member['active'],
            $member['admin'],
        ]);
        $selectMemberId->execute([$member['email']]);
        $memberIds[$key] = (int)$selectMemberId->fetchColumn();
    }

    $insertPayment = $pdo->prepare(
        'INSERT INTO kl_Einzahlungen (MitarbeiterID, Betrag, Datum)
         VALUES (?, ?, ?)'
    );
    foreach ($payments as $memberKey => $entries) {
        foreach ($entries as $entry) {
            $step = 'insert payment ' . $memberKey;
            $insertPayment->execute([
                $memberIds[$memberKey],
                gm_cents_to_decimal($entry['amount_cents']),
                $dates[$entry['date_key']],
            ]);
        }
    }

    $insertConsumption = $pdo->prepare(
        'INSERT INTO kl_Kaffeeverbrauch
         (MitarbeiterID, AnzahlStriche, Kosten, KostenproStrich, Datum, Eintragsart)
         VALUES (?, ?, ?, ?, ?, ?)'
    );
    foreach ($consumptions as $memberKey => $entries) {
        foreach ($entries as $entry) {
            $step = 'insert consumption ' . $memberKey;
            $costCents = $entry['marks'] * $entry['unit_price_cents'];
            $insertConsumption->execute([
                $memberIds[$memberKey],
                $entry['marks'],
                gm_cents_to_decimal($costCents),
                gm_cents_to_decimal($entry['unit_price_cents']),
                $dates[$entry['date_key']],
                $entry['entry_type'],
            ]);
        }
    }

    $step = 'insert notices';
    $insertNotice = $pdo->prepare('INSERT INTO kl_hinweise (nachricht, gueltig_bis) VALUES (?, ?)');
    $insertNotice->execute(['[GM] Aktiver Hinweis für Golden-Master-Test', $dates['notice_active']]);
    $insertNotice->execute(['[GM] Abgelaufener Hinweis für Golden-Master-Test', $dates['notice_expired']]);

    $metadata = [
        'golden_master_seed' => 'seeded',
        'golden_master_seed_year' => (string)gm_current_year(),
        'golden_master_seed_members' => (string)count($members),
        'golden_master_seed_source' => 'scripts/seed-golden-master.php',
    ];
    $insertMeta = $pdo->prepare(
        'INSERT INTO dev_baseline_metadata (meta_key, meta_value)
         VALUES (?, ?)
         ON DUPLICATE KEY UPDATE meta_value = VALUES(meta_value)'
    );
    foreach ($metadata as $key => $value) {
        $step = 'insert metadata ' . $key;
        $insertMeta->execute([$key, $value]);
    }

    $pdo->commit();
} catch (Throwable $e) {
    $pdo->rollBack();
    fwrite(STDERR, "Golden master seed failed at {$step}: {$e->getMessage()}\n");
    exit(1);
}

echo "Golden master fixtures seeded: " . count($members) . " members.\n";
