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

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

    const isAdmin = user.role === "admin" || user.role === "super_admin"
    const { searchParams } = new URL(request.url)
    const search = searchParams.get("search") || ""
    const statusId = searchParams.get("status") || ""

    let sql = `SELECT p.id, p.name, p.description, p.start_date, p.target_end_date, p.actual_end_date, p.budget, p.created_at,
                      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
               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
               WHERE p.deleted_at IS NULL`

    const params: any[] = []
    let idx = 1

    if (!isAdmin) {
      sql += ` AND (p.owner_id = $${idx} OR p.created_by = $${idx})`
      params.push(user.id)
      idx++
    }

    if (search) {
      sql += ` AND (p.name ILIKE $${idx} OR c.company_name ILIKE $${idx})`
      params.push(`%${search}%`)
      idx++
    }

    if (statusId) {
      sql += ` AND p.status_id = $${idx}`
      params.push(statusId)
      idx++
    }

    sql += ` ORDER BY p.created_at DESC`

    const result = await query(sql, params)
    return NextResponse.json(result.rows)
  } catch (error) {
    console.error("Projects API error:", error)
    return NextResponse.json({ error: "Failed to load projects" }, { status: 500 })
  }
}

export async function POST(request: NextRequest) {
  try {
    const user = await getSessionUser()
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

    const body = await request.json()
    const planningStatus = await query("SELECT id FROM project_statuses WHERE name = 'Planning'")
    const statusId = planningStatus.rows[0]?.id

    const result = await query(
      `INSERT INTO projects (customer_id, owner_id, name, description, status_id, start_date, target_end_date, budget, created_by)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING id`,
      [
        body.customerId,
        body.ownerId || user.id,
        body.name,
        body.description || null,
        statusId,
        body.startDate || null,
        body.targetEndDate || null,
        body.budget || null,
        user.id,
      ]
    )

    return NextResponse.json({ success: true, id: result.rows[0].id }, { status: 201 })
  } catch (error) {
    console.error("Projects POST error:", error)
    return NextResponse.json({ error: "Failed to create project" }, { status: 500 })
  }
}

export async function DELETE(request: NextRequest) {
  try {
    const user = await getSessionUser()
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

    const { searchParams } = new URL(request.url)
    const id = searchParams.get("id")
    if (!id) return NextResponse.json({ error: "id is required" }, { status: 400 })

    await query("UPDATE projects SET deleted_at = NOW() WHERE id = $1 AND deleted_at IS NULL", [id])
    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Projects DELETE error:", error)
    return NextResponse.json({ error: "Failed to delete project" }, { status: 500 })
  }
}
