<?php
declare(strict_types=1);

use App\Core\Database;

return function (Database $db): void {
    $ts   = date('Y-m-d H:i:s');
    $today = date('Y-m-d');

    // ── Helper: look up academy ID by code ──
    $academyId = function (string $code) use ($db): ?int {
        $row = $db->selectOne("SELECT id FROM academies WHERE code = ?", [$code]);
        return $row ? (int) ($row->id ?? $row['id']) : null;
    };

    // ── Helper: look up discipline ID by code ──
    $disciplineId = function (string $code) use ($db): ?int {
        $row = $db->selectOne("SELECT id FROM sport_disciplines WHERE code = ?", [$code]);
        return $row ? (int) ($row->id ?? $row['id']) : null;
    };

    // ── Helper: idempotent insert into activity_pricing ──
    $ensurePricing = function (string $pricingType, ?int $referenceId, float $memberRate, float $nonmemberRate) use ($db, $ts, $today): void {
        if ($referenceId === null) {
            return;
        }

        $existing = $db->selectOne(
            "SELECT id FROM activity_pricing WHERE pricing_type = ? AND reference_id = ? AND is_active = 1",
            [$pricingType, $referenceId]
        );
        if ($existing) {
            return;
        }

        $db->insert('activity_pricing', [
            'pricing_type'   => $pricingType,
            'reference_id'   => $referenceId,
            'member_rate'    => $memberRate,
            'nonmember_rate' => $nonmemberRate,
            'effective_from' => $today,
            'is_active'      => 1,
            'created_at'     => $ts,
            'updated_at'     => $ts,
        ]);
    };

    // ══════════════════════════════════════════════════════════════
    // Academy-level pricing (pricing_type = 'academy')
    // ══════════════════════════════════════════════════════════════

    // Football academies
    $ensurePricing('academy', $academyId('acad_anderlecht'),    400.00, 800.00);
    $ensurePricing('academy', $academyId('acad_mowahiba'),     400.00, 800.00);
    $ensurePricing('academy', $academyId('acad_rowad'),        350.00, 700.00);

    // Gymnastics academies
    $ensurePricing('academy', $academyId('acad_gym_artistic_m'), 350.00, 700.00);
    $ensurePricing('academy', $academyId('acad_gym_artistic_w'), 350.00, 700.00);
    $ensurePricing('academy', $academyId('acad_gym_aerobic'),    350.00, 700.00);

    // Swimming academies
    $ensurePricing('academy', $academyId('acad_swim_schools'),   300.00, 600.00);
    $ensurePricing('academy', $academyId('acad_swim_practice'),  400.00, 800.00);
    $ensurePricing('academy', $academyId('acad_swim_advanced'),  400.00, 800.00);

    // ══════════════════════════════════════════════════════════════
    // Discipline-level pricing for combat sports (pricing_type = 'discipline')
    // ══════════════════════════════════════════════════════════════

    $ensurePricing('discipline', $disciplineId('karate'),  300.00, 600.00);
    $ensurePricing('discipline', $disciplineId('kung_fu'), 300.00, 600.00);
};
