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

export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const user = await getSessionUser()
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

    const { id } = await params

    const result = await query(
      `SELECT p.id, p.name, p.description, p.start_date, p.target_end_date, p.actual_end_date, p.budget, p.custom_fields, p.created_at,
              ps.id AS status_id, ps.name AS status_name, ps.color AS status_color,
              c.id AS customer_id, c.company_name,
              u.id AS owner_id, u.first_name || ' ' || u.last_name AS owner_name, u.avatar_url AS owner_avatar,
              opp.id AS opportunity_id, opp.name AS opportunity_name
       FROM projects p
       JOIN project_statuses ps ON ps.id = p.status_id
       JOIN customers c ON c.id = p.customer_id
       JOIN users u ON u.id = p.owner_id
       LEFT JOIN opportunities opp ON opp.id = p.opportunity_id
       WHERE p.id = $1 AND p.deleted_at IS NULL`,
      [id]
    )

    if (result.rows.length === 0) {
      return NextResponse.json({ error: "Project not found" }, { status: 404 })
    }

    return NextResponse.json(result.rows[0])
  } catch (error) {
    console.error("Project detail API error:", error)
    return NextResponse.json({ error: "Failed to load project" }, { status: 500 })
  }
}

export async function PATCH(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const user = await getSessionUser()
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

    const { id } = await params
    const body = await request.json()

    const fields: string[] = []
    const values: any[] = []
    let idx = 1

    if (body.name !== undefined) { fields.push(`name = $${idx++}`); values.push(body.name) }
    if (body.description !== undefined) { fields.push(`description = $${idx++}`); values.push(body.description) }
    if (body.statusId !== undefined) { fields.push(`status_id = $${idx++}`); values.push(body.statusId) }
    if (body.startDate !== undefined) { fields.push(`start_date = $${idx++}`); values.push(body.startDate) }
    if (body.targetEndDate !== undefined) { fields.push(`target_end_date = $${idx++}`); values.push(body.targetEndDate) }
    if (body.actualEndDate !== undefined) { fields.push(`actual_end_date = $${idx++}`); values.push(body.actualEndDate) }
    if (body.budget !== undefined) { fields.push(`budget = $${idx++}`); values.push(body.budget) }
    if (body.ownerId !== undefined) { fields.push(`owner_id = $${idx++}`); values.push(body.ownerId) }
    if (body.customFields !== undefined) { fields.push(`custom_fields = $${idx++}`); values.push(JSON.stringify(body.customFields)) }

    if (fields.length === 0) {
      return NextResponse.json({ error: "No fields to update" }, { status: 400 })
    }

    fields.push(`updated_at = NOW()`)
    values.push(id)

    const sql = `UPDATE projects SET ${fields.join(", ")} WHERE id = $${idx} AND deleted_at IS NULL RETURNING id`
    const result = await query(sql, values)

    if (result.rows.length === 0) {
      return NextResponse.json({ error: "Project not found" }, { status: 404 })
    }

    return NextResponse.json({ success: true, id: result.rows[0].id })
  } catch (error) {
    console.error("Project PATCH error:", error)
    return NextResponse.json({ error: "Failed to update project" }, { status: 500 })
  }
}
