import { NextRequest, NextResponse } from "next/server"
import prisma from "@/lib/prisma"
import { resolveOrgId } from "@/lib/org"

export async function GET(request: NextRequest) {
  try {
    if (!prisma) return NextResponse.json({ error: "DB not configured" }, { status: 503 })
    const orgId = await resolveOrgId(request.headers.get("x-org-id") || "demo")
    if (!orgId) return NextResponse.json({ error: "Org not found" }, { status: 404 })

    const org = await prisma.organization.findUnique({ where: { id: orgId } })
    if (!org) return NextResponse.json({ error: "Org not found" }, { status: 404 })

    return NextResponse.json({
      id: org.id,
      name: org.name,
      slug: org.slug,
      country: org.country,
      bankName: org.bankName || "",
      bankSortCode: org.bankSortCode || "",
      bankAccountNo: org.bankAccountNo || "",
      bankAccountName: org.bankAccountName || "",
      refPrefix: org.refPrefix,
      logo: org.logo,
      primaryColor: org.primaryColor,
      gcAccessToken: org.gcAccessToken ? "••••••••" : "",
      gcEnvironment: org.gcEnvironment,
    })
  } catch (error) {
    console.error("Settings GET error:", error)
    return NextResponse.json({ error: "Internal error" }, { status: 500 })
  }
}

export async function PATCH(request: NextRequest) {
  try {
    if (!prisma) return NextResponse.json({ error: "DB not configured" }, { status: 503 })
    const orgId = await resolveOrgId(request.headers.get("x-org-id") || "demo")
    if (!orgId) return NextResponse.json({ error: "Org not found" }, { status: 404 })

    const body = await request.json()
    const allowed = ["name", "bankName", "bankSortCode", "bankAccountNo", "bankAccountName", "refPrefix", "primaryColor", "logo", "gcAccessToken", "gcEnvironment"]
    const data: Record<string, string> = {}
    for (const key of allowed) {
      if (key in body && body[key] !== undefined && body[key] !== "••••••••") {
        data[key] = body[key]
      }
    }

    const org = await prisma.organization.update({
      where: { id: orgId },
      data,
    })

    return NextResponse.json({ success: true, name: org.name })
  } catch (error) {
    console.error("Settings PATCH error:", error)
    return NextResponse.json({ error: "Internal error" }, { status: 500 })
  }
}
