import { NextRequest, NextResponse } from "next/server";
import { queryRows } from "@/lib/db";
import { getSession } from "@/lib/session";

export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const body = await request.json();
  const conditions: string[] = [];
  const params: unknown[] = [];
  let idx = 1;

  if (body.year) {
    conditions.push(`TO_CHAR(IM.regdate, 'YYYY') = $${idx++}`);
    params.push(body.year);
  }
  if (body.customer_name) {
    conditions.push(`COALESCE((SELECT supply_name FROM supply_mng WHERE objid::text = CM.customer_objid LIMIT 1), '') LIKE '%' || $${idx++} || '%'`);
    params.push(body.customer_name);
  }
  if (body.invoice_date_from) {
    conditions.push(`IM.issuance_date >= $${idx++}`);
    params.push(body.invoice_date_from);
  }
  if (body.invoice_date_to) {
    conditions.push(`IM.issuance_date <= $${idx++}`);
    params.push(body.invoice_date_to);
  }

  const whereClause = conditions.length > 0 ? "AND " + conditions.join(" AND ") : "";

  const sql = `
    SELECT IM.objid::text AS "OBJID",
      IM.objid::text AS "INVOICE_NO",
      COALESCE((SELECT supply_name FROM supply_mng WHERE objid::text = CM.customer_objid LIMIT 1), '') AS "CUSTOMER_NAME",
      CM.contract_no AS "PROJECT_NO", CM.project_name AS "PROJECT_NAME",
      IM.issuance_date AS "INVOICE_DATE",
      COALESCE(IM.price_sum::numeric, 0) AS "SUPPLY_AMOUNT",
      ROUND(COALESCE(IM.price_sum::numeric, 0) * 0.1) AS "TAX_AMOUNT",
      ROUND(COALESCE(IM.price_sum::numeric, 0) * 1.1) AS "TOTAL_AMOUNT",
      COALESCE((SELECT code_name FROM comm_code WHERE code_id = IM.status LIMIT 1), IM.status) AS "STATUS_NAME",
      COALESCE((SELECT user_name FROM user_info WHERE user_id = IM.writer LIMIT 1), '') AS "WRITER_NAME"
    FROM invoice_mgmt IM
    LEFT JOIN contract_mgmt CM ON CM.objid::text = IM.parent_objid
    WHERE 1=1 ${whereClause}
    ORDER BY IM.regdate DESC
  `;

  const rows = await queryRows(sql, params);
  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
