//
//  Game.swift
//  SportsTime
//

import Foundation

struct Game: Identifiable, Codable, Hashable {
    let id: String  // Canonical ID: "game_mlb_2026_bos_nyy_0401"
    let homeTeamId: String  // FK: "team_mlb_bos"
    let awayTeamId: String  // FK: "team_mlb_nyy"
    let stadiumId: String   // FK: "stadium_mlb_fenway_park"
    let dateTime: Date
    let sport: Sport
    let season: String
    let isPlayoff: Bool
    let broadcastInfo: String?

    init(
        id: String,
        homeTeamId: String,
        awayTeamId: String,
        stadiumId: String,
        dateTime: Date,
        sport: Sport,
        season: String,
        isPlayoff: Bool = false,
        broadcastInfo: String? = nil
    ) {
        self.id = id
        self.homeTeamId = homeTeamId
        self.awayTeamId = awayTeamId
        self.stadiumId = stadiumId
        self.dateTime = dateTime
        self.sport = sport
        self.season = season
        self.isPlayoff = isPlayoff
        self.broadcastInfo = broadcastInfo
    }

    var gameDate: Date {
        Calendar.current.startOfDay(for: dateTime)
    }

    /// Alias for TripPlanningEngine compatibility
    var startTime: Date { dateTime }

    var gameTime: String {
        let formatter = DateFormatter()
        formatter.timeStyle = .short
        return formatter.string(from: dateTime)
    }

    var formattedDate: String {
        let formatter = DateFormatter()
        formatter.dateStyle = .medium
        return formatter.string(from: dateTime)
    }

    var dayOfWeek: String {
        let formatter = DateFormatter()
        formatter.dateFormat = "EEEE"
        return formatter.string(from: dateTime)
    }
}

extension Game: Equatable {
    static func == (lhs: Game, rhs: Game) -> Bool {
        lhs.id == rhs.id
    }
}

// MARK: - Rich Game Model (with resolved references)

struct RichGame: Identifiable, Hashable, Codable {
    let game: Game
    let homeTeam: Team
    let awayTeam: Team
    let stadium: Stadium

    var id: String { game.id }

    var matchupDescription: String {
        "\(awayTeam.abbreviation) @ \(homeTeam.abbreviation)"
    }

    var fullMatchupDescription: String {
        "\(awayTeam.fullName) at \(homeTeam.fullName)"
    }

    var venueDescription: String {
        "\(stadium.name), \(stadium.city)"
    }

    /// Game time formatted in the stadium's local timezone with timezone indicator
    var localGameTime: String {
        let formatter = DateFormatter()
        formatter.dateFormat = "h:mm a z"
        formatter.timeZone = stadium.timeZone ?? .current
        return formatter.string(from: game.dateTime)
    }

    /// Game time formatted in the stadium's local timezone without timezone indicator
    var localGameTimeShort: String {
        let formatter = DateFormatter()
        formatter.dateFormat = "h:mm a"
        formatter.timeZone = stadium.timeZone ?? .current
        return formatter.string(from: game.dateTime)
    }
}
