import { NextResponse } from "next/server"
import { sql } from "@/lib/db"

export async function GET() {
  try {
    let promotions: any[] = []

    try {
      promotions = await sql`SELECT * FROM promotions ORDER BY created_at DESC`
    } catch (e) {
      console.log("Promotions table not found, returning empty")
    }

    return NextResponse.json({ promotions, banners: [] })
  } catch (error) {
    console.error("Error fetching promotions:", error)
    return NextResponse.json({ promotions: [], banners: [] })
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json()
    const { title, description, target_type, action_url, image_url, start_date, end_date, position } = body

    const result = await sql`
      INSERT INTO promotions (title, description, target_type, action_url, image_url, start_date, end_date, position, is_active)
      VALUES (${title}, ${description}, ${target_type || "all"}, ${action_url || null}, ${image_url || null}, ${start_date || null}, ${end_date || null}, ${position || "home"}, true)
      RETURNING *
    `
    return NextResponse.json(result[0])
  } catch (error) {
    console.error("Error creating promotion:", error)
    return NextResponse.json({ error: "Failed to create promotion" }, { status: 500 })
  }
}
