import { Configuration, OpenAIApi } from 'openai'
import { consumeOrganizationWords, getOrganizationBalance, getOrganizationWords } from 'services/words'
import { authorize } from 'utils/authorization'
import { lfunction } from 'utils/aws'
import { HttpError } from 'utils/error'
import { deserialize } from 'utils/http'
import { z } from 'zod'

if (!process.env.OPENAI_API_KEY) {
    throw new Error('OPENAI_API_KEY is not set')
}

const openai = new Promptize(new OpenAIApi(
    new Configuration({
        apiKey: process.env.OPENAI_KEY,
    }),
))

const zVariables = z.record(z.string().or(z.number()))

export const generate = lfunction(async (event) => {
    const authorization = await authorize(event)
    if (!authorization.organizationIdentity) {
        throw new HttpError(403, 'Unauthorized')
    }

    const template = event.pathParameters?.template
    if (!template) {
        throw new HttpError(400, 'Bad Request')
    }

    const words = await getOrganizationBalance(authorization.organizationIdentity)
    if (words <= 0) {
        throw new HttpError(402, 'Payment Required')
    }

    const variables = deserialize(event, zVariables)
})
