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

export async function GET() {
  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 accounts = await query(
      `SELECT fa.id, fa.label, fa.profile_path, fa.is_active,
              fa.last_scrape_at, fa.last_success_at, fa.last_error_at,
              fa.last_error_message, fa.consecutive_failures,
              fa.flagged, fa.flagged_at, fa.flagged_reason,
              fa.created_at, fa.updated_at,
              COALESCE(sl.leads_found, 0) AS last_leads_found,
              sl.success AS last_success,
              sl.detected_flag AS last_detected_flag
       FROM facebook_accounts fa
       LEFT JOIN LATERAL (
         SELECT leads_found, success, detected_flag
         FROM facebook_scrape_logs
         WHERE account_id = fa.id
         ORDER BY created_at DESC
         LIMIT 1
       ) sl ON TRUE
       ORDER BY fa.created_at ASC`
    )

    return NextResponse.json(accounts.rows)
  } catch (error) {
    console.error("Facebook accounts GET error:", error)
    return NextResponse.json({ error: "Failed to load Facebook accounts" }, { status: 500 })
  }
}

export async function POST(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 { label, profilePath } = await request.json()
    if (!label?.trim() || !profilePath?.trim()) {
      return NextResponse.json({ error: "Label and profile path are required" }, { status: 400 })
    }

    const cookieFile = `${profilePath.replace(/\\+$/, '')}\\cookies.sqlite`
    const result = await query(
      `INSERT INTO facebook_accounts (label, profile_path, cookie_file)
       VALUES ($1, $2, $3)
       RETURNING id, label, profile_path, is_active, created_at`,
      [label.trim(), profilePath.trim(), cookieFile]
    )

    return NextResponse.json(result.rows[0], { status: 201 })
  } catch (error) {
    console.error("Facebook accounts POST error:", error)
    return NextResponse.json({ error: "Failed to create Facebook account" }, { status: 500 })
  }
}
