<?php

namespace App\Command;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(
    name: 'app:db:reset-sequences',
    description: 'Resets all PostgreSQL sequences to the max ID of their tables.',
)]
class ResetSequencesCommand extends Command
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager
    ) {
        parent::__construct();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        $conn = $this->entityManager->getConnection();

        // 1. Fetch all sequences linked to tables
        $sql = "
            SELECT 
                t.relname as table_name,
                a.attname as column_name,
                s.relname as sequence_name
            FROM pg_class s
            JOIN pg_depend d ON d.objid = s.oid
            JOIN pg_class t ON d.refobjid = t.oid
            JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = d.refobjsubid
            WHERE s.relkind = 'S';
        ";

        try {
            $sequences = $conn->fetchAllAssociative($sql);
        } catch (\Exception $e) {
            $io->error('Error fetching sequences: ' . $e->getMessage());
            return Command::FAILURE;
        }

        $io->title('Resetting Database Sequences');
        $io->progressStart(count($sequences));

        $count = 0;
        foreach ($sequences as $seq) {
            $table = $seq['table_name'];
            $column = $seq['column_name'];
            $sequence = $seq['sequence_name'];

            // 2. Get Max ID
            // Using quote_identifier for safety
            $maxSql = sprintf(
                'SELECT MAX(%s) FROM %s',
                $conn->quoteIdentifier($column),
                $conn->quoteIdentifier($table)
            );
            
            $maxId = $conn->fetchOne($maxSql);
            $maxId = $maxId ? (int)$maxId : 0;

            // 3. Reset Sequence
            // setval(sequence, next_value) -> we set it to maxId so next is maxId+1? 
            // Postgres setval(seq, val, true) sets current value. Next will be val+1.
            // If table is empty (maxId=0), we can set to 1 (is_called=false) or just 1.
            
            if ($maxId > 0) {
                $conn->executeQuery(sprintf("SELECT setval('%s', %d)", $sequence, $maxId));
            } else {
                // Table empty, reset to 1
                $conn->executeQuery(sprintf("SELECT setval('%s', 1, false)", $sequence));
            }

            $io->progressAdvance();
            $count++;
        }

        $io->progressFinish();
        $io->success(sprintf('Successfully reset %d sequences.', $count));

        return Command::SUCCESS;
    }
}
