import Foundation

struct FitnessAPI {
    private let api = APIClient.shared

    // MARK: - Entries

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

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

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

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

    // MARK: - Foods

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

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

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

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

    // MARK: - Goals

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

    // MARK: - Templates

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

    func logTemplate(id: String, date: String) async throws {
        try await api.postVoid(
            "/api/fitness/templates/\(id)/log",
            queryItems: [URLQueryItem(name: "date", value: date)]
        )
    }

    // MARK: - AI Split

    func splitFood(text: String, mealType: String) async throws -> [FoodItem] {
        let request = SplitFoodRequest(text: text, mealType: mealType)
        return try await api.post("/api/fitness/foods/split", body: request)
    }
}
