<?php

declare(strict_types=1);

namespace OCA\Mitgliederverwaltung\Migration;

use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\IDBConnection;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;

/**
 * Migration: Seed default Stufen (Woelflinge, Pfadfinder, Rover).
 *
 * Per Req 2.3, the app should ship with three default Stufen
 * so that a fresh installation is immediately usable.
 *
 * Part of Issue #128.
 */
class Version000014Date20260409000000 extends SimpleMigrationStep {

    private IDBConnection $db;

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

    public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void {
        // Only seed if the table is empty (avoid duplicates on re-run)
        $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'], \OCP\DB\QueryBuilder\IQueryBuilder::PARAM_INT),
                    'age_range_min' => $qb->createNamedParameter($stufe['age_range_min'], $stufe['age_range_min'] !== null ? \OCP\DB\QueryBuilder\IQueryBuilder::PARAM_INT : \OCP\DB\QueryBuilder\IQueryBuilder::PARAM_STR),
                    'age_range_max' => $qb->createNamedParameter($stufe['age_range_max'], $stufe['age_range_max'] !== null ? \OCP\DB\QueryBuilder\IQueryBuilder::PARAM_INT : \OCP\DB\QueryBuilder\IQueryBuilder::PARAM_STR),
                    'color' => $qb->createNamedParameter($stufe['color']),
                ]);
            $qb->executeStatement();
        }

        $output->info('Seeded 3 default Stufen: Woelflinge, Pfadfinder, Rover.');
    }
}
