import { Auth } from "../../auth"
import { AppRuntime } from "../../effect/app-runtime"
import * as prompts from "@clack/prompts"
import { UI } from "../ui"
import { Plugin } from "../../plugin"
import { Instance } from "../../project/instance"
import type { Hooks } from "@saeeol/plugin"
import { Effect } from "effect"

type PluginAuth = NonNullable<Hooks["auth"]>

export const put = (key: string, info: Auth.Info) =>
  AppRuntime.runPromise(
    Effect.gen(function* () {
      const auth = yield* Auth.Service
      yield* auth.set(key, info)
    }),
  )

export async function handlePluginAuth(
  plugin: { auth: PluginAuth },
  provider: string,
  methodName?: string,
): Promise<boolean> {
  let index = 0
  if (methodName) {
    const match = plugin.auth.methods.findIndex((x) => x.label.toLowerCase() === methodName.toLowerCase())
    if (match === -1) {
      prompts.log.error(
        `Unknown method "${methodName}" for ${provider}. Available: ${plugin.auth.methods.map((x) => x.label).join(", ")}`,
      )
      process.exit(1)
    }
    index = match
  } else if (plugin.auth.methods.length > 1) {
    const method = await prompts.select({
      message: "Login method",
      options: plugin.auth.methods.map((x, index) => ({ label: x.label, value: index.toString() })),
    })
    if (prompts.isCancel(method)) throw new UI.CancelledError()
    index = parseInt(method)
  }
  const method = plugin.auth.methods[index]

  await new Promise((r) => setTimeout(r, 10))
  const inputs: Record<string, string> = {}
  if (method.prompts) {
    for (const prompt of method.prompts) {
      if (prompt.when) {
        const value = inputs[prompt.when.key]
        if (value === undefined) continue
        const matches = prompt.when.op === "eq" ? value === prompt.when.value : value !== prompt.when.value
        if (!matches) continue
      }
      if (prompt.condition && !prompt.condition(inputs)) continue
      if (prompt.type === "select") {
        const value = await prompts.select({ message: prompt.message, options: prompt.options })
        if (prompts.isCancel(value)) throw new UI.CancelledError()
        inputs[prompt.key] = value
      } else {
        const value = await prompts.text({
          message: prompt.message,
          placeholder: prompt.placeholder,
          validate: prompt.validate ? (v) => prompt.validate!(v ?? "") : undefined,
        })
        if (prompts.isCancel(value)) throw new UI.CancelledError()
        inputs[prompt.key] = value
      }
    }
  }

  if (method.type === "oauth") {
    const authorize = await method.authorize(inputs)
    if (authorize.url) prompts.log.info("Go to: " + authorize.url)

    if (authorize.method === "auto") {
      if (authorize.instructions) prompts.log.info(authorize.instructions)
      const spinner = prompts.spinner()
      spinner.start("Waiting for authorization...")
      const result = await authorize.callback()
      if (result.type === "failed") spinner.stop("Failed to authorize", 1)
      if (result.type === "success") {
        const saveProvider = result.provider ?? provider
        if ("refresh" in result) {
          const { type: _, provider: __, refresh, access, expires, ...extra } = result
          await put(saveProvider, { type: "oauth", refresh, access, expires, ...extra })
        }
        if ("key" in result) await put(saveProvider, { type: "api", key: result.key })
        spinner.stop("Login successful")
      }
    }

    if (authorize.method === "code") {
      const code = await prompts.text({
        message: "Paste the authorization code here: ",
        validate: (x) => (x && x.length > 0 ? undefined : "Required"),
      })
      if (prompts.isCancel(code)) throw new UI.CancelledError()
      const result = await authorize.callback(code)
      if (result.type === "failed") prompts.log.error("Failed to authorize")
      if (result.type === "success") {
        const saveProvider = result.provider ?? provider
        if ("refresh" in result) {
          const { type: _, provider: __, refresh, access, expires, ...extra } = result
          await put(saveProvider, { type: "oauth", refresh, access, expires, ...extra })
        }
        if ("key" in result) await put(saveProvider, { type: "api", key: result.key })
        prompts.log.success("Login successful")
      }
    }

    prompts.outro("Done")
    return true
  }

  if (method.type === "api") {
    const key = await prompts.password({
      message: "Enter your API key",
      validate: (x) => (x && x.length > 0 ? undefined : "Required"),
    })
    if (prompts.isCancel(key)) throw new UI.CancelledError()
    const metadata = Object.keys(inputs).length ? { metadata: inputs } : {}
    if (!method.authorize) {
      await put(provider, { type: "api", key, ...metadata })
      prompts.outro("Done")
      return true
    }
    const result = await method.authorize(inputs)
    if (result.type === "failed") prompts.log.error("Failed to authorize")
    if (result.type === "success") {
      const saveProvider = result.provider ?? provider
      await put(saveProvider, { type: "api", key: result.key ?? key, ...metadata })
      prompts.log.success("Login successful")
    }
    prompts.outro("Done")
    return true
  }

  return false
}

export function resolvePluginProviders(input: {
  hooks: Hooks[]
  existingProviders: Record<string, unknown>
  disabled: Set<string>
  enabled?: Set<string>
  providerNames: Record<string, string | undefined>
}): Array<{ id: string; name: string }> {
  const seen = new Set<string>()
  const result: Array<{ id: string; name: string }> = []
  for (const hook of input.hooks) {
    if (!hook.auth) continue
    const id = hook.auth.provider
    if (seen.has(id)) continue
    seen.add(id)
    if (Object.hasOwn(input.existingProviders, id)) continue
    if (input.disabled.has(id)) continue
    if (input.enabled && !input.enabled.has(id)) continue
    result.push({ id, name: input.providerNames[id] ?? id })
  }
  return result
}
