import OpenAI from "openai";

export default {
  async fetch(request, env, ctx) {
    const openai = new OpenAI({
      apiKey: env.OPENAI_API_KEY
    })
    try {
      const userPrompt = await request.json()
      const messages = [
        {
          role: "system",
          content: "Determine the city referenced by the user and return information about it."
        },
        ...userPrompt
      ];
      const format = {
        "format": {
            "type": "json_schema",
            "name": "Info-Cities",
            "schema": {
              "type": "object",
              "properties": {
                "city": {
                  "type": "string",
                  "description": "The name of the city."
                },
                "country": {
                  "type": "string",
                  "description": "The country where the city is located."
                },
                "language": {
                  "type": "string",
                  "description": "The main spoken language in the city."
                },
                "currency": {
                  "type": "string",
                  "description": "The official currency used in the city."
                },
                "attractions": {
                  "type": "array",
                  "description": "Five tourists attractions in this city.",
                  "items": { "type": "string" },
                }
              },
              "required": ["city", "country", "language", "currency", "attractions"],
              "additionalProperties": false
            },
            "strict": true
        }
      };
      const response = await openai.responses.create({
        model: "gpt-5",
        input: messages,
        text: format,
        store: false,
        max_output_tokens: 2000
      });
      return new Response(JSON.stringify(response))
    } catch(e) {
      return new Response(JSON.stringify({ error: e.message }), {
        status: 500 });
    }
  }
};