// Copyright © 2024 Ryan Booker. All rights reserved.

import ArgumentParser
import Foundation

public enum Endpoint: String {
    static let baseUrl = URL(string: "https://kagi.com/api/v0/")!

    case fastGPT
    case search
    case summarize

    var httpMethod: String {
        switch self {
        case .search:
            return "GET"
        case .fastGPT, .summarize:
            return "POST"
        }
    }

    var url: URL {
        URL(string: rawValue.lowercased(), relativeTo: Self.baseUrl)!
    }

    var request: URLRequest {
        var request = URLRequest(url: url)
        request.httpMethod = httpMethod

        if httpMethod == "POST" {
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        }
        return request
    }

    public var authorizedRequest: URLRequest {
        get throws {
            guard let apiToken = ProcessInfo.processInfo.environment["FASTGPT_API_TOKEN"] else {
                throw ValidationError("API key is missing. Set the environment variable FASTGPT_API_TOKEN.")
            }

            var request = self.request
            request.setValue("Bot \(apiToken)", forHTTPHeaderField: "Authorization")
            return request
        }
    }
}