// ── Settings: Single Facebook Account ───────────────────────────────────────
// PATCH /api/settings/facebook/accounts/[id]
//   — Update a Facebook scraping account (label, profile path, active, unflag)
//
// Auth: admin/super_admin only

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

// ── 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 })
    if (user.role !== "admin" && user.role !== "super_admin") {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 })
    }

    const { id } = await params
    const body = await request.json()
    const fields: string[] = []
    const values: any[] = []
    let idx = 1

    // Build dynamic SET clause for partial updates
    if (body.isActive !== undefined) {
      fields.push(`is_active = $${idx++}`)
      values.push(body.isActive)
    }
    if (body.label !== undefined) {
      fields.push(`label = $${idx++}`)
      values.push(body.label.trim())
    }
    if (body.profilePath !== undefined) {
      // Update both profile_path and the derived cookie_file path
      fields.push(`profile_path = $${idx++}, cookie_file = $${idx}`)
      values.push(body.profilePath.trim())
      values.push(`${body.profilePath.replace(/\\+$/, '')}\\cookies.sqlite`)
      idx++
    }
    if (body.unflag === true) {
      // Clear flag status and reset failure counter
      fields.push(`flagged = FALSE, flagged_at = NULL, flagged_reason = NULL, consecutive_failures = 0`)
    }

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

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

    await query(
      `UPDATE facebook_accounts SET ${fields.join(", ")} WHERE id = $${idx}`,
      values
    )

    const updated = await query(
      `SELECT id, label, profile_path, is_active, flagged, flagged_reason,
              consecutive_failures, updated_at
       FROM facebook_accounts WHERE id = $1`,
      [id]
    )

    return NextResponse.json(updated.rows[0] || { success: true })
  } catch (error) {
    console.error("Facebook accounts PATCH error:", error)
    return NextResponse.json({ error: "Failed to update Facebook account" }, { status: 500 })
  }
}
