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

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 result = await query(
      `INSERT INTO tasks (title, description, status, project_id, milestone_id, assigned_to, assigned_by, created_at, updated_at)
       VALUES ($1, $2, 'pending', $3, $4, $5, $6, NOW(), NOW()) RETURNING id`,
      [
        body.title,
        body.description || null,
        body.projectId || null,
        body.milestoneId || null,
        body.assignedTo || null,
        user.id,
      ]
    )

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

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

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

    if (!id) return NextResponse.json({ error: "id is required" }, { status: 400 })

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

    if (fields.status !== undefined) { setClauses.push(`status = $${idx++}`); values.push(fields.status) }
    if (fields.title !== undefined) { setClauses.push(`title = $${idx++}`); values.push(fields.title) }
    if (fields.assignedTo !== undefined) { setClauses.push(`assigned_to = $${idx++}`); values.push(fields.assignedTo) }

    if (fields.status === "completed") {
      setClauses.push(`completed_at = NOW()`)
    }

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

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

    await query(
      `UPDATE tasks SET ${setClauses.join(", ")} WHERE id = $${idx} AND deleted_at IS NULL`,
      values
    )

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Tasks PATCH error:", error)
    return NextResponse.json({ error: "Failed to update task" }, { status: 500 })
  }
}
