// ── Settings: Facebook Scrape Logs ──────────────────────────────────────────
// GET /api/settings/facebook/logs?accountId=&limit=&offset=
//   — List Facebook scraping session logs, optionally filtered by account
//
// Auth: admin/super_admin only

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

// ── GET ──────────────────────────────────────────────────────────────────────

export async function GET(request: NextRequest) {
  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 { searchParams } = new URL(request.url)
    const accountId = searchParams.get("accountId")
    const limit = parseInt(searchParams.get("limit") || "50", 10)
    const offset = parseInt(searchParams.get("offset") || "0", 10)

    let sql = `SELECT sl.id, sl.account_id, fa.label AS account_label,
                      sl.started_at, sl.completed_at, sl.success,
                      sl.leads_found, sl.error_message, sl.detected_flag,
                      sl.created_at
               FROM facebook_scrape_logs sl
               JOIN facebook_accounts fa ON fa.id = sl.account_id`
    const params: any[] = []
    let paramIdx = 1

    if (accountId) {
      sql += ` WHERE sl.account_id = $${paramIdx++}`
      params.push(accountId)
    }

    sql += ` ORDER BY sl.created_at DESC LIMIT $${paramIdx++} OFFSET $${paramIdx++}`
    params.push(limit, offset)

    const result = await query(sql, params)
    return NextResponse.json(result.rows)
  } catch (error) {
    console.error("Facebook scrape logs GET error:", error)
    return NextResponse.json({ error: "Failed to load scrape logs" }, { status: 500 })
  }
}
