import Foundation

struct FitnessAPI {
    private let api = APIClient.shared
    private let basePath = "/api/fitness"

    // MARK: - Entries

    func getEntries(date: String) async throws -> [FoodEntry] {
        try await api.get(
            "\(basePath)/entries",
            queryItems: [URLQueryItem(name: "date", value: date)]
        )
    }

    func createEntry(_ request: CreateEntryRequest) async throws -> FoodEntry {
        try await api.post("\(basePath)/entries", body: request)
    }

    func deleteEntry(id: String) async throws -> SuccessResponse {
        try await api.delete("\(basePath)/entries/\(id)")
    }

    // MARK: - Goals

    func getGoalsForDate(date: String) async throws -> DailyGoal {
        try await api.get(
            "\(basePath)/goals/for-date",
            queryItems: [URLQueryItem(name: "date", value: date)]
        )
    }

    func updateGoals(_ request: UpdateGoalsRequest) async throws {
        try await api.putVoid("\(basePath)/goals", body: request)
    }

    func updateEntry(id: String, body: UpdateEntryRequest) async throws -> FoodEntry {
        try await api.patch("\(basePath)/entries/\(id)", body: body)
    }

    // MARK: - Foods

    func getFoods(limit: Int = 100) async throws -> [Food] {
        try await api.get(
            "\(basePath)/foods",
            queryItems: [URLQueryItem(name: "limit", value: String(limit))]
        )
    }

    func searchFoods(query: String, limit: Int = 20) async throws -> [Food] {
        try await api.get(
            "\(basePath)/foods/search",
            queryItems: [
                URLQueryItem(name: "q", value: query),
                URLQueryItem(name: "limit", value: String(limit)),
            ]
        )
    }

    func getRecentFoods(limit: Int = 20) async throws -> [RecentFood] {
        try await api.get(
            "\(basePath)/foods/recent",
            queryItems: [URLQueryItem(name: "limit", value: String(limit))]
        )
    }

    func getFood(id: String) async throws -> Food {
        try await api.get("\(basePath)/foods/\(id)")
    }

    // MARK: - Templates

    func getTemplates() async throws -> [MealTemplate] {
        try await api.get("\(basePath)/templates")
    }

    func logTemplate(id: String, mealType: String, entryDate: String) async throws -> TemplateLogResponse {
        struct LogBody: Encodable {
            let mealType: String
            let entryDate: String
        }
        return try await api.post(
            "\(basePath)/templates/\(id)/log",
            body: LogBody(mealType: mealType, entryDate: entryDate)
        )
    }

    // MARK: - Assistant (raw)

    func sendAssistantMessage(data: Data) async throws -> Data {
        try await api.rawPost(path: "/api/assistant/fitness", data: data)
    }
}
