<?php

declare(strict_types=1);

final class DevController
{
    public static function backfillWeights(): void
    {
        header('Content-Type: text/plain; charset=utf-8');

        // sécurité : local only
        $addr = $_SERVER['REMOTE_ADDR'] ?? '';
        if ($addr !== '127.0.0.1' && $addr !== '::1') {
            http_response_code(403);
            echo "Forbidden\n";
            return;
        }

        $db = DB::pdo();
        $db->beginTransaction();
        try {
            // Copie chaque note médicale ayant un poids -> measurements (sans dupliquer le même jour)
            $sql = "
            INSERT INTO measurements(animal_id, measured_at, type, value, unit, notes)
            SELECT mn.animal_id, mn.noted_at, 'weight', mn.weight_kg, 'kg', 'backfill from medical_notes'
            FROM medical_notes mn
            WHERE mn.weight_kg IS NOT NULL
            AND NOT EXISTS (
                SELECT 1 FROM measurements m
                WHERE m.animal_id = mn.animal_id
                AND m.type = 'weight'
                AND date(m.measured_at) = date(mn.noted_at)
                )
                ";
            $count = $db->exec($sql);
            $db->commit();

            echo 'Backfill OK. Inserted rows: ' . (int) $count . "\n";
            echo "Retourne sur /animal?id=...\n";
        } catch (Throwable $e) {
            $db->rollBack();
            http_response_code(500);
            echo 'Backfill FAILED: ' . $e->getMessage() . "\n";
        }
    }

    public static function backup(): void
    {
        header('Content-Type: text/plain; charset=utf-8');
        $addr = $_SERVER['REMOTE_ADDR'] ?? '';
        if ($addr !== '127.0.0.1' && $addr !== '::1') {
            http_response_code(403);
            echo "Forbidden\n";
            return;
        }

        $src = __DIR__ . '/../../data/refuge.sqlite';
        $dir = __DIR__ . '/../../storage/backups';
        if (!is_dir($dir)) {
            mkdir($dir, 0775, true);
        }

        $dst = $dir . '/refuge-' . date('Ymd-His') . '.sqlite';

        // Copie cohérente SQLite
        $pdo = DB::pdo();
        $pdo->exec('VACUUM INTO ' . $pdo->quote($dst));

        echo 'Backup OK: ' . basename($dst) . "\n";
    }

    public static function backfillMovements(): void
    {
        $pdo = DB::pdo();

        $animals = $pdo->query('SELECT * FROM animals')->fetchAll(PDO::FETCH_ASSOC);

        $pdo->beginTransaction();

        try {
            foreach ($animals as $a) {
                // Vérifie si déjà migré
                $check = $pdo->prepare('SELECT COUNT(*) FROM animal_movements WHERE animal_id = ?');
                $check->execute([$a['id']]);
                if ($check->fetchColumn() > 0) {
                    continue;
                }

                // ENTRY
                $stmt = $pdo->prepare("
                INSERT INTO animal_movements
                (animal_id, kind, moved_at, provenance, place, note)
                VALUES (?, 'entry', ?, ?, ?, ?)
                ");

                $stmt->execute([
                    $a['id'],
                    $a['created_at'] ?? date('Y-m-d H:i:s'),
                    'Migration ancienne donnée',
                    $a['rescue_address'] ?? '',
                    'Migration automatique',
                ]);

                // EXIT (si statut final)
                if (in_array($a['status'], ['adopted', 'deceased', 'transferred', 'fugue'])) {
                    $stmt = $pdo->prepare("
                    INSERT INTO animal_movements
                    (animal_id, kind, moved_at, exit_type, place, note)
                    VALUES (?, 'exit', ?, ?, ?, ?)
                    ");

                    $stmt->execute([
                        $a['id'],
                        $a['updated_at'] ?? date('Y-m-d H:i:s'),
                        $a['status'],
                        $a['current_address'] ?? '',
                        'Migration automatique',
                    ]);
                }
            }

            $pdo->commit();
            echo 'Backfill OK.';
        } catch (Throwable $e) {
            $pdo->rollBack();
            echo 'Erreur: ' . $e->getMessage();
        }
    }
}
