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

// Utility function to generate a unique customerId like CID-56415445
async function generateUniqueCustomerId() {
  let customerId;
  let exists = true;

  while (exists) {
    const randomNum = Math.floor(1000 + Math.random() * 9000); // 8-digit random number
    customerId = `CID-${randomNum}`;

    const [existing] = await db.query(
      `SELECT customerId FROM kyc WHERE customerId = ? LIMIT 1`,
      [customerId]
    );

    exists = existing.length > 0;
  }

  return customerId;
}

// GET: Get all KYC or specific one by ID or customerId
export async function GET(req) {
  try {
    const url = new URL(req.url);
    const id = url.searchParams.get("id");
    const customerId = url.searchParams.get("customerId");
    const page = parseInt(url.searchParams.get("page")) || 1;
    const limit = parseInt(url.searchParams.get("limit")) || 10;
    const offset = (page - 1) * limit;
    const orderByCreated = url.searchParams.get("orderby_created") === "true";

    if (id) {
      const [rows] = await db.query("SELECT * FROM kyc WHERE kyc_id = ?", [id]);
      return NextResponse.json({ success: true, data: rows });
    }

    if (customerId) {
      const [rows] = await db.query("SELECT * FROM kyc WHERE customerId = ?", [customerId]);
      return NextResponse.json({ success: true, data: rows });
    }

    const [countResult] = await db.query("SELECT COUNT(*) AS total FROM kyc");
    const totalRecords = countResult[0].total;
    const totalPages = Math.ceil(totalRecords / limit);

    let query = "SELECT * FROM kyc";
    if (orderByCreated) {
      query += " ORDER BY created_at DESC";
    }
    query += " LIMIT ? OFFSET ?";
    const [rows] = await db.query(query, [limit, offset]);

    return NextResponse.json({
      success: true,
      data: rows,
      pagination: {
        page,
        limit,
        totalRecords,
        totalPages,
      },
    });
  } catch (error) {
    return NextResponse.json(
      { success: false, message: "Error fetching KYC", error: error.message },
      { status: 500 }
    );
  }
}

// POST: Create a new KYC entry with auto-generated customerId
export async function POST(req) {
  try {
    const data = await req.json();
    const {
      legalName,
      tradeName,
      entityType,
      otherEntityType,
      incorporationDate,
      incorporationCountry,
      regNumber,
      taxId,
      regAddress1,
      regAddress2,
      regCity,
      regState,
      regCountry,
      regPostal,
      billSameAsReg,
      billAddress1,
      billAddress2,
      billCity,
      billState,
      billCountry,
      billPostal,
      primaryName,
      primaryDesignation,
      primaryPhone,
      primaryEmail,
      altName,
      altDesignation,
      altPhone,
      altEmail,
      docTradeLicense,
      docTaxCert,
      docSignatoryId,
      docPOA,
      declarationConfirmed,
    } = data;

    const customerId = await generateUniqueCustomerId();
    const createdAt = new Date().toISOString().slice(0, 19).replace("T", " ");

    const insertQuery = `
      INSERT INTO kyc (
        customerId,
        legal_name, trade_name, entity_type, other_entity_type,
        incorporation_date, incorporation_country, registration_number, tax_id,
        reg_address_1, reg_address_2, reg_city, reg_state, reg_country, reg_postal,
        bill_same_as_reg, bill_address_1, bill_address_2, bill_city, bill_state, bill_country, bill_postal,
        primary_name, primary_designation, primary_phone, primary_email,
        alt_name, alt_designation, alt_phone, alt_email,
        doc_trade_license, doc_tax_cert, doc_signatory_id, doc_poa,
        declaration_confirmed, created_at
      ) VALUES (
        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
      )
    `;

    const values = [
      customerId,
      legalName,
      tradeName,
      entityType,
      otherEntityType,
      incorporationDate,
      incorporationCountry,
      regNumber,
      taxId,
      regAddress1,
      regAddress2,
      regCity,
      regState,
      regCountry,
      regPostal,
      billSameAsReg ? "1" : "0",
      billAddress1,
      billAddress2,
      billCity,
      billState,
      billCountry,
      billPostal,
      primaryName,
      primaryDesignation,
      primaryPhone,
      primaryEmail,
      altName,
      altDesignation,
      altPhone,
      altEmail,
      docTradeLicense?.url || "",
      docTaxCert?.url || "",
      docSignatoryId?.url || "",
      docPOA?.url || "",
      declarationConfirmed ? "1" : "0",
      createdAt,
    ];

    await db.query(insertQuery, values);

    return NextResponse.json({
      success: true,
      message: "KYC submitted successfully",
      customerId,
    });
  } catch (error) {
    return NextResponse.json(
      { success: false, message: "Error submitting KYC", error: error.message },
      { status: 500 }
    );
  }
}



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

// // GET: Get all KYC or specific one by ID or customerId
// export async function GET(req) {
//   try {
//     const url = new URL(req.url);
//     const id = url.searchParams.get("id");
//     const customerId = url.searchParams.get("customerId");
//     const page = parseInt(url.searchParams.get("page")) || 1;
//     const limit = parseInt(url.searchParams.get("limit")) || 10;
//     const offset = (page - 1) * limit;
//     const orderByCreated = url.searchParams.get("orderby_created") === "true";

//     if (id) {
//       const [rows] = await db.query("SELECT * FROM kyc WHERE kyc_id = ?", [id]);
//       return NextResponse.json({ success: true, data: rows });
//     }

//     if (customerId) {
//       const [rows] = await db.query("SELECT * FROM kyc WHERE customerId = ?", [customerId]);
//       return NextResponse.json({ success: true, data: rows });
//     }

//     const [countResult] = await db.query("SELECT COUNT(*) AS total FROM kyc");
//     const totalRecords = countResult[0].total;
//     const totalPages = Math.ceil(totalRecords / limit);

//     let query = "SELECT * FROM kyc";
//     if (orderByCreated) {
//       query += " ORDER BY created_at DESC";
//     }
//     query += " LIMIT ? OFFSET ?";
//     const [rows] = await db.query(query, [limit, offset]);

//     return NextResponse.json({
//       success: true,
//       data: rows,
//       pagination: {
//         page,
//         limit,
//         totalRecords,
//         totalPages,
//       },
//     });
//   } catch (error) {
//     return NextResponse.json(
//       { success: false, message: "Error fetching KYC", error: error.message },
//       { status: 500 }
//     );
//   }
// }

// // POST: Create a new KYC entry with auto-generated customerId
// export async function POST(req) {
//   try {
//     const data = await req.json();
//     const {
//       legalName,
//       tradeName,
//       entityType,
//       otherEntityType,
//       incorporationDate,
//       incorporationCountry,
//       regNumber,
//       taxId,
//       regAddress1,
//       regAddress2,
//       regCity,
//       regState,
//       regCountry,
//       regPostal,
//       billSameAsReg,
//       billAddress1,
//       billAddress2,
//       billCity,
//       billState,
//       billCountry,
//       billPostal,
//       primaryName,
//       primaryDesignation,
//       primaryPhone,
//       primaryEmail,
//       altName,
//       altDesignation,
//       altPhone,
//       altEmail,
//       docTradeLicense,
//       docTaxCert,
//       docSignatoryId,
//       docPOA,
//       declarationConfirmed,
//     } = data;

//     const currentYear = new Date().getFullYear();

//     // Get last customerId for this year
//     const [latest] = await db.query(
//       `SELECT customerId FROM kyc WHERE customerId LIKE ? ORDER BY kyc_id DESC LIMIT 1`,
//       [`CID-${currentYear}-%`]
//     );

//     let newSeq = 1;
//     if (latest.length > 0) {
//       const lastRef = latest[0].customerId;
//       const lastSeq = parseInt(lastRef.split("-")[2]);
//       newSeq = lastSeq + 1;
//     }

//     const customerId = `CID-${currentYear}-${String(newSeq).padStart(4, "0")}`;
//     const createdAt = new Date().toISOString().slice(0, 19).replace("T", " ");

//     const insertQuery = `
//       INSERT INTO kyc (
//         customerId,
//         legal_name, trade_name, entity_type, other_entity_type,
//         incorporation_date, incorporation_country, registration_number, tax_id,
//         reg_address_1, reg_address_2, reg_city, reg_state, reg_country, reg_postal,
//         bill_same_as_reg, bill_address_1, bill_address_2, bill_city, bill_state, bill_country, bill_postal,
//         primary_name, primary_designation, primary_phone, primary_email,
//         alt_name, alt_designation, alt_phone, alt_email,
//         doc_trade_license, doc_tax_cert, doc_signatory_id, doc_poa,
//         declaration_confirmed, created_at
//       ) VALUES (
//         ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
//       )
//     `;

//     const values = [
//       customerId,
//       legalName,
//       tradeName,
//       entityType,
//       otherEntityType,
//       incorporationDate,
//       incorporationCountry,
//       regNumber,
//       taxId,
//       regAddress1,
//       regAddress2,
//       regCity,
//       regState,
//       regCountry,
//       regPostal,
//       billSameAsReg ? "1" : "0",
//       billAddress1,
//       billAddress2,
//       billCity,
//       billState,
//       billCountry,
//       billPostal,
//       primaryName,
//       primaryDesignation,
//       primaryPhone,
//       primaryEmail,
//       altName,
//       altDesignation,
//       altPhone,
//       altEmail,
//       docTradeLicense?.url || "",
//       docTaxCert?.url || "",
//       docSignatoryId?.url || "",
//       docPOA?.url || "",
//       declarationConfirmed ? "1" : "0",
//       createdAt,
//     ];

//     await db.query(insertQuery, values);

//     return NextResponse.json({
//       success: true,
//       message: "KYC submitted successfully",
//       customerId,
//     });
//   } catch (error) {
//     return NextResponse.json(
//       { success: false, message: "Error submitting KYC", error: error.message },
//       { status: 500 }
//     );
//   }
// }

