import Foundation

final class APIClient {
    static let shared = APIClient()

    let baseURL = URL(string: "https://banyaro.app")!
    var token: String?

    private let session: URLSession = .shared
    private let decoder: JSONDecoder = {
        let d = JSONDecoder()
        d.keyDecodingStrategy = .convertFromSnakeCase
        return d
    }()
    private let encoder: JSONEncoder = {
        let e = JSONEncoder()
        e.keyEncodingStrategy = .convertToSnakeCase
        return e
    }()

    func get<T: Decodable>(_ path: String) async throws -> T {
        try await perform(method: "GET", path: path, body: nil)
    }

    func post<T: Decodable, B: Encodable>(_ path: String, body: B) async throws -> T {
        let data = try encoder.encode(body)
        return try await perform(method: "POST", path: path, body: data)
    }

    func post<T: Decodable>(_ path: String) async throws -> T {
        try await perform(method: "POST", path: path, body: nil)
    }

    /// Multipart-File-Upload. Server-Endpunkte wie POST /api/routes/{id}/photo
    /// erwarten Feld `file` mit JPEG-Bytes.
    @discardableResult
    func uploadFile(
        _ path: String,
        fieldName: String = "file",
        filename: String,
        data: Data,
        mimeType: String = "image/jpeg"
    ) async throws -> Data {
        let boundary = "Boundary-\(UUID().uuidString)"
        let url = baseURL.appending(path: path)
        var req = URLRequest(url: url)
        req.httpMethod = "POST"
        req.setValue("application/json", forHTTPHeaderField: "Accept")
        if let token {
            req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        }
        req.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

        var body = Data()
        body.append("--\(boundary)\r\n".data(using: .utf8)!)
        body.append("Content-Disposition: form-data; name=\"\(fieldName)\"; filename=\"\(filename)\"\r\n".data(using: .utf8)!)
        body.append("Content-Type: \(mimeType)\r\n\r\n".data(using: .utf8)!)
        body.append(data)
        body.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)

        let (responseData, response) = try await session.upload(for: req, from: body)
        guard let http = response as? HTTPURLResponse else {
            throw APIError.invalidResponse
        }
        guard (200..<300).contains(http.statusCode) else {
            throw APIError.server(status: http.statusCode, message: Self.parseErrorDetail(from: responseData))
        }
        return responseData
    }

    private func perform<T: Decodable>(method: String, path: String, body: Data?) async throws -> T {
        let url = baseURL.appending(path: path)
        var req = URLRequest(url: url)
        req.httpMethod = method
        req.setValue("application/json", forHTTPHeaderField: "Accept")
        if let token {
            req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        }
        if let body {
            req.setValue("application/json", forHTTPHeaderField: "Content-Type")
            req.httpBody = body
        }

        let (data, response) = try await session.data(for: req)
        guard let http = response as? HTTPURLResponse else {
            throw APIError.invalidResponse
        }
        if http.statusCode == 401 {
            NotificationCenter.default.post(name: .apiUnauthorized, object: nil)
            throw APIError.unauthorized
        }
        guard (200..<300).contains(http.statusCode) else {
            let detail = Self.parseErrorDetail(from: data)
            throw APIError.server(status: http.statusCode, message: detail)
        }
        return try decoder.decode(T.self, from: data)
    }

    /// Convenience for DELETE with no response body.
    func delete(_ path: String) async throws {
        let url = baseURL.appending(path: path)
        var req = URLRequest(url: url)
        req.httpMethod = "DELETE"
        if let token { req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") }
        let (data, response) = try await session.data(for: req)
        guard let http = response as? HTTPURLResponse else { throw APIError.invalidResponse }
        if http.statusCode == 401 {
            NotificationCenter.default.post(name: .apiUnauthorized, object: nil)
            throw APIError.unauthorized
        }
        guard (200..<300).contains(http.statusCode) else {
            throw APIError.server(status: http.statusCode, message: Self.parseErrorDetail(from: data))
        }
    }

    /// Convenience for PATCH with JSON body, decoding the response.
    func patch<T: Decodable, B: Encodable>(_ path: String, body: B) async throws -> T {
        let data = try encoder.encode(body)
        let url = baseURL.appending(path: path)
        var req = URLRequest(url: url)
        req.httpMethod = "PATCH"
        req.setValue("application/json", forHTTPHeaderField: "Accept")
        req.setValue("application/json", forHTTPHeaderField: "Content-Type")
        if let token { req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") }
        req.httpBody = data
        let (respData, response) = try await session.data(for: req)
        guard let http = response as? HTTPURLResponse else { throw APIError.invalidResponse }
        if http.statusCode == 401 {
            NotificationCenter.default.post(name: .apiUnauthorized, object: nil)
            throw APIError.unauthorized
        }
        guard (200..<300).contains(http.statusCode) else {
            throw APIError.server(status: http.statusCode, message: Self.parseErrorDetail(from: respData))
        }
        return try decoder.decode(T.self, from: respData)
    }

    /// FastAPI returns errors as {"detail": "message"} or {"detail": [{...}]}.
    private static func parseErrorDetail(from data: Data) -> String? {
        if let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
            if let s = obj["detail"] as? String { return s }
            if let arr = obj["detail"] as? [[String: Any]],
               let first = arr.first,
               let msg = first["msg"] as? String { return msg }
        }
        return nil
    }
}
