import { serve } from "bun"
import { handleGiteaWebhook } from "../bridge"
import { startDiscord } from "../discord"
import { listLogFiles, log, readLogFileRaw } from "../log"
import { LogsPage } from "./logs"

await startDiscord()

const server = serve({
  port: parseInt(process.env.PORT || "3000"),
  routes: {
    "/": {
      GET: () => new Response("🌵"),
      POST: () => new Response("Use /gitea/webhook for POST requests", { status: 400 }),
    },
    "/gitea/webhook": {
      POST: async (req) => {
        const payload = await req.json()
        const eventType = req.headers.get("X-Gitea-Event") || "unknown"
        const repo = (payload as any)?.repository?.full_name || "unknown"
        const sender = (payload as any)?.sender?.login as string | undefined
        const ref = (payload as any)?.ref as string | undefined
        log({ type: "webhook", eventType, repo, sender, ref })

        try {
          await handleGiteaWebhook(payload, eventType as any)
          return new Response("OK", { status: 200 })
        } catch (error) {
          log({ type: "error", error, context: `webhook ${eventType} ${repo}` })
          return new Response("Error", { status: 500 })
        }
      },
    },
    "/logs": {
      GET: (req) => {
        const accept = req.headers.get("Accept") || ""
        const wantsRaw = !accept.includes("text/html")
        if (!wantsRaw) return LogsPage(req)

        const file = new URL(req.url).searchParams.get("file")
        if (!file) {
          const files = listLogFiles()
          return Response.json(files)
        }
        try {
          const raw = readLogFileRaw(file)
          if (!raw) return new Response("Not found", { status: 404 })
          return new Response(raw, { headers: { "Content-Type": "application/jsonl" } })
        } catch {
          return new Response("Internal server error", { status: 500 })
        }
      },
    },
    "/discord/auth": async () => {
      const permissions = 536870912 // from https://discord.com/developers/applications
      const authorizeUrl = `https://discord.com/oauth2/authorize?client_id=${process.env.DISCORD_CLIENT_ID}&scope=bot&permissions=${permissions}`

      const html = (
        <html>
          <body>
            <h1>Authenticate spike</h1>
            <a href={authorizeUrl}>Authorize</a>
          </body>
        </html>
      )
      return new Response(html.toString(), { headers: { "Content-Type": "text/html" } })
    },
  },

  development: process.env.NODE_ENV !== "production" && { hmr: true, console: true },
})

log({ type: "startup", detail: `Spike running at ${server.url}:${server.port}` })
