import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { query } from "@/lib/db"

export async function GET() {
  try {
    const user = await getSessionUser()
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
    if (user.role !== "admin" && user.role !== "super_admin") {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 })
    }

    const result = await query(`SELECT * FROM company_settings ORDER BY updated_at DESC LIMIT 1`)
    const row = result.rows[0]

    if (!row) {
      return NextResponse.json({
        companyName: "Coastal IT Solutions",
        companyEmail: "info@coastalit.com",
        companyPhone: "(555) 123-4567",
        companyWebsite: "https://coastalit.com",
        companyAddress: "123 Business Ave, Suite 100, San Francisco, CA 94105",
      })
    }

    return NextResponse.json({
      companyName: row.company_name || "",
      companyEmail: row.company_email || "",
      companyPhone: row.company_phone || "",
      companyWebsite: row.company_website || "",
      companyAddress: row.company_address || "",
    })
  } catch (error) {
    console.error("Company settings GET error:", error)
    return NextResponse.json({ error: "Failed to load company settings" }, { status: 500 })
  }
}

export async function PATCH(request: NextRequest) {
  try {
    const user = await getSessionUser()
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
    if (user.role !== "admin" && user.role !== "super_admin") {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 })
    }

    const body = await request.json()

    await query(
      `UPDATE company_settings SET
        company_name = $1, company_email = $2, company_phone = $3,
        company_website = $4, company_address = $5, updated_by = $6, updated_at = NOW()`,
      [
        body.companyName || "",
        body.companyEmail || "",
        body.companyPhone || "",
        body.companyWebsite || "",
        body.companyAddress || "",
        user.id,
      ],
    )

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Company settings PATCH error:", error)
    return NextResponse.json({ error: "Failed to save company settings" }, { status: 500 })
  }
}
