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 { searchParams } = new URL(request.url)
    const projectId = searchParams.get("projectId") || ""
    const userId = searchParams.get("userId") || ""
    const from = searchParams.get("from") || ""
    const to = searchParams.get("to") || ""

    let sql = `SELECT te.id, te.description, te.date, te.duration_minutes, te.billable, te.hourly_rate, te.created_at,
                      u.first_name || ' ' || u.last_name AS user_name,
                      p.name AS project_name
               FROM time_entries te
               JOIN users u ON u.id = te.user_id
               LEFT JOIN projects p ON p.id = te.project_id`

    const conditions: string[] = ["te.user_id IS NOT NULL"]
    const params: any[] = []
    let idx = 1

    if (!(user.role === "admin" || user.role === "super_admin")) {
      conditions.push(`te.user_id = $${idx++}`)
      params.push(user.id)
    } else if (userId) {
      conditions.push(`te.user_id = $${idx++}`)
      params.push(userId)
    }
    if (projectId) {
      conditions.push(`te.project_id = $${idx++}`)
      params.push(projectId)
    }
    if (from) { conditions.push(`te.date >= $${idx++}`); params.push(from) }
    if (to) { conditions.push(`te.date <= $${idx++}`); params.push(to) }

    sql += ` WHERE ${conditions.join(" AND ")} ORDER BY te.date DESC, te.created_at DESC LIMIT 100`

    const result = await query(sql, params)
    return NextResponse.json(result.rows)
  } catch (error) {
    console.error("Time entries API error:", error)
    return NextResponse.json({ error: "Failed to load time entries" }, { 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 duration = body.durationMinutes || 0

    if (duration <= 0) {
      return NextResponse.json({ error: "Duration must be greater than 0" }, { status: 400 })
    }

    const result = await query(
      `INSERT INTO time_entries (user_id, project_id, milestone_id, task_id, description, date, start_time, end_time, duration_minutes, billable, hourly_rate)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING id`,
      [
        body.userId || user.id,
        body.projectId || null,
        body.milestoneId || null,
        body.taskId || null,
        body.description || null,
        body.date || new Date().toISOString().split("T")[0],
        body.startTime || null,
        body.endTime || null,
        duration,
        body.billable !== false,
        body.hourlyRate || null,
      ]
    )

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

export async function DELETE(request: NextRequest) {
  try {
    await getSessionUser()
    const { searchParams } = new URL(request.url)
    const id = searchParams.get("id")
    if (!id) return NextResponse.json({ error: "id required" }, { status: 400 })
    await query("DELETE FROM time_entries WHERE id = $1", [id])
    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Time entries DELETE error:", error)
    return NextResponse.json({ error: "Failed to delete entry" }, { status: 500 })
  }
}
