import Foundation

// MARK: - TMDB API Response Models

struct TMDBMovieListResponse: Decodable, Sendable {
    let page: Int
    let results: [TMDBMovie]
    let totalPages: Int
    let totalResults: Int
}

struct TMDBMovie: Codable, Sendable, Identifiable {
    let id: Int
    let title: String
    let releaseDate: String?
    let posterPath: String?
    let overview: String?
    let voteAverage: Double?

    var posterURL: URL? {
        guard let posterPath = posterPath else { return nil }
        return URL(string: "\(Constants.TMDB.imageBaseURL)\(posterPath)")
    }
}

// MARK: - TMDB Cache Model

struct TMDBCache: Codable, Sendable {
    let movies: [TMDBMovie]
    let cachedAt: Date

    var isStale: Bool {
        Date().timeIntervalSince(cachedAt) > Constants.TMDB.cacheTTL
    }
}

// MARK: - TMDB TV Show Models

struct TMDBTVShow: Codable, Sendable, Identifiable {
    let id: Int
    let name: String
    let posterPath: String?
    let firstAirDate: String?
    let lastAirDate: String?  // Key field for "recently aired"
    let popularity: Double?
    let voteAverage: Double?

    enum CodingKeys: String, CodingKey {
        case id, name, popularity
        case posterPath = "poster_path"
        case firstAirDate = "first_air_date"
        case lastAirDate = "last_air_date"
        case voteAverage = "vote_average"
    }

    var posterURL: URL? {
        guard let posterPath = posterPath else { return nil }
        return URL(string: "\(Constants.TMDB.imageBaseURL)\(posterPath)")
    }
}

struct TMDBTVListResponse: Codable, Sendable {
    let page: Int?
    let results: [TMDBTVShow]
    let totalPages: Int?
    let totalResults: Int?

    enum CodingKeys: String, CodingKey {
        case page, results
        case totalPages = "total_pages"
        case totalResults = "total_results"
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.page = try container.decodeIfPresent(Int.self, forKey: .page)
        self.results = (try? container.decode([TMDBTVShow].self, forKey: .results)) ?? []
        self.totalPages = try container.decodeIfPresent(Int.self, forKey: .totalPages)
        self.totalResults = try container.decodeIfPresent(Int.self, forKey: .totalResults)
    }
}

// MARK: - TMDB TV Cache Model

struct TMDBTVCache: Codable, Sendable {
    let shows: [TMDBTVShow]
    let cachedAt: Date

    var isStale: Bool {
        Date().timeIntervalSince(cachedAt) > Constants.TMDB.cacheTTL
    }
}
