<?php

declare(strict_types=1);

namespace OCA\Mitgliederverwaltung\Migration;

use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;
use OCP\Migration\IOutput;
use OCP\Migration\IRepairStep;

/**
 * Repair step: ensure default Stufen exist.
 *
 * The original seed migration (Version000014) runs inside a transaction
 * that silently fails on PostgreSQL and SQLite. This repair step runs
 * after all migrations complete (outside the transaction) and inserts
 * the default Stufen only if the table is empty.
 */
class SeedDefaultStufen implements IRepairStep {

    private IDBConnection $db;

    public function __construct(IDBConnection $db) {
        $this->db = $db;
    }

    public function getName(): string {
        return 'Seed default Stufen (Wölflinge, Pfadfinder, Rover)';
    }

    public function run(IOutput $output): void {
        $qb = $this->db->getQueryBuilder();
        $qb->select($qb->createFunction('COUNT(*)'))
            ->from('mv_stufen');
        $result = $qb->executeQuery();
        $count = (int)$result->fetchOne();
        $result->closeCursor();

        if ($count > 0) {
            $output->info('Stufen table already has data, skipping seed.');
            return;
        }

        $defaultStufen = [
            ['name' => 'Wölflinge',  'sort_order' => 0, 'age_range_min' => 6,  'age_range_max' => 11,   'color' => '#FFD700'],
            ['name' => 'Pfadfinder', 'sort_order' => 1, 'age_range_min' => 12, 'age_range_max' => 17,   'color' => '#228B22'],
            ['name' => 'Rover',      'sort_order' => 2, 'age_range_min' => 18, 'age_range_max' => null,  'color' => '#DD1212'],
        ];

        foreach ($defaultStufen as $stufe) {
            $qb = $this->db->getQueryBuilder();
            $qb->insert('mv_stufen')
                ->values([
                    'name' => $qb->createNamedParameter($stufe['name']),
                    'sort_order' => $qb->createNamedParameter($stufe['sort_order'], IQueryBuilder::PARAM_INT),
                    'age_range_min' => $qb->createNamedParameter($stufe['age_range_min'], IQueryBuilder::PARAM_INT),
                    'age_range_max' => $qb->createNamedParameter($stufe['age_range_max'], $stufe['age_range_max'] !== null ? IQueryBuilder::PARAM_INT : IQueryBuilder::PARAM_STR),
                    'color' => $qb->createNamedParameter($stufe['color']),
                ]);
            $qb->executeStatement();
        }

        $output->info('Seeded 3 default Stufen.');
    }
}
