<?php

namespace App\Services;

use App\Core\Database;
use PDO;

final class FixtureService
{
    private PDO $db;

    public function __construct()
    {
        $this->db = Database::connection();
    }

    public function generateLeague(int $tournamentId, ?string $startDate = null): array
    {
        $teams = $this->teams($tournamentId);
        $created = [];
        $date = new \DateTimeImmutable($startDate ?: 'next saturday 18:00');

        for ($i = 0; $i < count($teams); $i++) {
            for ($j = $i + 1; $j < count($teams); $j++) {
                $stmt = $this->db->prepare(
                    'INSERT INTO matches (tournament_id, phase, scheduled_at, home_team_id, away_team_id, status)
                     VALUES (:tournament_id, "regular", :scheduled_at, :home_team_id, :away_team_id, "scheduled")'
                );
                $stmt->execute([
                    'tournament_id' => $tournamentId,
                    'scheduled_at' => $date->format('Y-m-d H:i:s'),
                    'home_team_id' => $teams[$i]['id'],
                    'away_team_id' => $teams[$j]['id'],
                ]);
                $created[] = (int) $this->db->lastInsertId();
                $date = $date->modify('+2 hours');
            }
        }

        return ['created' => count($created), 'match_ids' => $created];
    }

    private function teams(int $tournamentId): array
    {
        $stmt = $this->db->prepare('SELECT id, name FROM teams WHERE tournament_id = :id ORDER BY id');
        $stmt->execute(['id' => $tournamentId]);
        return $stmt->fetchAll();
    }
}
