// ── Events: Single Event ─────────────────────────────────────────────────────
// PATCH  /api/events/[id]  — Update an event (with permission checks & lead auto-close)
// DELETE /api/events/[id]  — Delete an event (hard delete, creator only)
//
// Auth: authenticated; participants/developers can update limited fields;
//       only the creator can delete or edit core event details.

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

// ── PATCH ────────────────────────────────────────────────────────────────────

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 { title, description, eventType, startTime, endTime, durationMinutes, status, participantId, developerId, participantNotes, clientName, clientEmail, clientPhone } = await request.json()

    // Fetch current event with creator + participant details
    const existing = await query(
      `SELECT e.user_id, e.participant_id, e.developer_id, e.lead_id, e.title, e.description, e.participant_notes, e.event_type,
              e.start_time, e.end_time, e.duration_minutes, e.status, e.client_name, e.client_email, e.client_phone,
              u.email AS u_email, u.first_name AS u_first, u.last_name AS u_last,
              p.email AS p_email, p.first_name AS p_first, p.last_name AS p_last
       FROM scheduled_events e
       JOIN users u ON u.id = e.user_id
       LEFT JOIN users p ON p.id = e.participant_id
       WHERE e.id = $1`,
      [id],
      user.id,
    )

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

    const old = existing.rows[0]
    const isCreator = old.user_id === user.id
    const isParticipant = old.participant_id === user.id
    const isDeveloper = old.developer_id === user.id

    if (!isCreator && !isParticipant && !isDeveloper) {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 })
    }

    // Non-creators cannot change core event details (title, type, time, participants)
    if (!isCreator && (
      (title !== undefined && title !== old.title) ||
      (eventType !== undefined && eventType !== old.event_type) ||
      (startTime !== undefined && startTime !== old.start_time) ||
      (endTime !== undefined && endTime !== old.end_time) ||
      (durationMinutes !== undefined && durationMinutes !== old.duration_minutes) ||
      (participantId !== undefined && participantId !== old.participant_id) ||
      (developerId !== undefined && developerId !== old.developer_id)
    )) {
      return NextResponse.json({ error: "Only the creator can edit event details" }, { status: 403 })
    }

    // COALESCE-based partial update: only overwrite provided fields
    const result = await query(
      `UPDATE scheduled_events SET
        title = COALESCE($1, title),
        description = COALESCE($2, description),
        participant_notes = COALESCE($3, participant_notes),
        event_type = COALESCE($4, event_type),
        start_time = CASE WHEN $4::varchar = 'website_creation' THEN NULL ELSE COALESCE($5, start_time) END,
        end_time = CASE WHEN $4::varchar = 'website_creation' THEN NULL ELSE COALESCE($6, end_time) END,
        duration_minutes = CASE WHEN $4::varchar = 'website_creation' THEN NULL ELSE COALESCE($7, duration_minutes) END,
        status = COALESCE($8, status),
        participant_id = COALESCE($9, participant_id),
        developer_id = COALESCE($10, developer_id),
        client_name = COALESCE($11, client_name),
        client_email = COALESCE($12, client_email),
        client_phone = COALESCE($13, client_phone),
        updated_at = NOW()
       WHERE id = $14
       RETURNING id, user_id, participant_id, developer_id, lead_id, conversation_id, title, description, participant_notes, event_type, start_time, end_time, duration_minutes, client_name, client_email, client_phone, status, created_at`,
      [
        title || null,
        description ?? null,
        participantNotes ?? null,
        eventType || null,
        startTime || null,
        endTime ?? null,
        durationMinutes ?? null,
        status || null,
        participantId ?? null,
        developerId ?? null,
        clientName ?? null,
        clientEmail ?? null,
        clientPhone ?? null,
        id,
      ],
      user.id,
    )

    const r = result.rows[0]

    // Auto-close the associated lead when a developer marks the event as completed
    if (status === "completed" && r.lead_id) {
      const stageResult = await query("SELECT id FROM lead_stages WHERE name = 'Closed Won'")
      if (stageResult.rows.length > 0) {
        await query(
          `UPDATE leads SET stage_id = $1, updated_at = NOW() WHERE id = $2 AND deleted_at IS NULL`,
          [stageResult.rows[0].id, r.lead_id],
        )
      }
    }

    // Send reschedule email if core fields changed
    const isChanged = r.start_time !== old.start_time || r.end_time !== old.end_time ||
      r.title !== old.title || r.event_type !== old.event_type ||
      r.status !== old.status

    if (isChanged && r.participant_id && r.participant_id !== user.id) {
      sendEventRescheduled({
        creatorName: `${user.firstName} ${user.lastName}`,
        creatorEmail: user.email,
        participantName: old.p_first ? `${old.p_first} ${old.p_last}` : null,
        participantEmail: old.p_email || null,
        title: r.title,
        description: r.description || undefined,
        eventType: r.event_type,
        startTime: r.start_time,
        endTime: r.end_time || undefined,
        durationMinutes: r.duration_minutes || undefined,
      }).catch((err) => console.error("Reschedule email error:", err))
    }

    // Fetch creator info to return in the response
    const creatorResult = await query(
      `SELECT u.id, u.first_name, u.last_name, u.email, u.avatar_url,
              ur.role_id, r.name AS role_name, r.display_name AS role_display
       FROM users u
       LEFT JOIN user_roles ur ON ur.user_id = u.id
       LEFT JOIN roles r ON r.id = ur.role_id
       WHERE u.id = $1`,
      [old.user_id],
    )
    const creatorInfo = creatorResult.rows[0]
    const participantInfo = old.participant_id ? { id: old.participant_id, name: `${old.p_first} ${old.p_last}` || old.participant_id, email: old.p_email || null } : null
    const developerInfo = old.developer_id ? { id: old.developer_id, name: "", email: "" } : null

    return NextResponse.json({
      event: {
        id: r.id,
        userId: r.user_id,
        participantId: r.participant_id,
        developerId: r.developer_id,
        leadId: r.lead_id,
        conversationId: r.conversation_id,
        title: r.title,
        description: r.description,
        participantNotes: r.participant_notes,
        eventType: r.event_type,
        startTime: r.start_time,
        endTime: r.end_time,
        durationMinutes: r.duration_minutes,
        status: r.status,
        creator: creatorInfo ? { id: creatorInfo.id, name: `${creatorInfo.first_name} ${creatorInfo.last_name}`, email: creatorInfo.email, role: creatorInfo.role_display || creatorInfo.role_name, avatar: creatorInfo.avatar_url } : { id: old.user_id, name: "Unknown" },
        participant: participantInfo,
        developer: developerInfo,
        lead: null,
        clientName: r.client_name || null,
        clientEmail: r.client_email || null,
        clientPhone: r.client_phone || null,
        createdAt: r.created_at,
      },
    })
  } catch (error) {
    console.error("Events PATCH error:", error)
    return NextResponse.json({ error: "Failed to update event" }, { status: 500 })
  }
}

// ── DELETE ───────────────────────────────────────────────────────────────────

export async function DELETE(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 existing = await query(
      `SELECT user_id FROM scheduled_events WHERE id = $1`,
      [id],
      user.id,
    )

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

    // Only the event creator can delete
    if (existing.rows[0].user_id !== user.id) {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 })
    }

    await query(`DELETE FROM scheduled_events WHERE id = $1`, [id], user.id)

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Events DELETE error:", error)
    return NextResponse.json({ error: "Failed to delete event" }, { status: 500 })
  }
}
