import { NextResponse } from "next/server";
import { db } from "../../lib/db";
import { getServerSession } from "next-auth";
import { authOptions } from "../auth/[...nextauth]/route";

export async function GET(req: Request) {
  try {
    const { searchParams } = new URL(req.url);
    const search = searchParams.get("search") || "";

    let where = "WHERE 1=1";

    if (search) {
      where += `
        AND (
          u.code LIKE '%${search}%'
          OR u.name LIKE '%${search}%'
          OR u.category LIKE '%${search}%'
        )
      `;
    }

    // u.created_at,
    // u.updated_at,
    const [rows]: any = await db.query(`
      SELECT 
        u.id,
        u.code,
        u.name,
        u.category,
        u.symbol,
        u.is_base,
        u.is_active,
        COUNT(i.id) AS total_items
      FROM units u
      LEFT JOIN items i 
        ON i.units = u.code
      ${where}
      GROUP BY 
        u.id,
        u.code,
        u.name,
        u.category,
        u.symbol,
        u.is_base,
        u.is_active
        ORDER BY u.code DESC
        `);
        // u.created_at,
        // u.updated_at

    return NextResponse.json({
      units: rows ?? []
    });

  } catch (err: any) {
    console.error("API /satuan error:", err);

    return NextResponse.json({
      units: [],
      message: "Failed load units",
      error: err?.message
    }, { status: 500 });
  }
}


/* ================= POST ================= */

export async function POST(req: Request) {
  try {
    const body = await req.json();

    const {
      code,
      name,
      category,
      symbol,
      is_base,
      is_active,
    } = body;

    /* ================= SESSION USER ================= */
    const session = await getServerSession(authOptions);
    const created_by = session?.user?.id ? Number(session.user.id) : null;

    if (!code || !name) {
      return NextResponse.json(
        { message: "Code dan Name wajib diisi" },
        { status: 400 }
      );
    }

    const normalizedCode = code.toUpperCase().trim();

    /* ===============================
       CHECK DUPLICATE CODE
    =============================== */
    const [existing]: any = await db.query(
      `SELECT id FROM units WHERE code = ? LIMIT 1`,
      [normalizedCode]
    );

    if (existing.length > 0) {
      return NextResponse.json(
        {
          success: false,
          message: "Code unit sudah digunakan",
        },
        { status: 409 }
      );
    }

    /* ===============================
       INSERT DATA
    =============================== */
    const result: any = await db.query(
      `
      INSERT INTO units 
      (code, name, category, symbol, is_base, is_active)
      VALUES (?, ?, ?, ?, ?, ?)
      `,
      [
        normalizedCode,
        name,
        category || "LAINNYA",
        symbol || null,
        is_base ? 1 : 0,
        is_active ? 1 : 0,
      ]
    );

    const unitId = result?.[0]?.insertId;

    /* ===============================
       ACTIVITY LOG
    =============================== */
    await db.query(
      `
      INSERT INTO activity_logs
      (entity, entity_id, action, description, created_by)
      VALUES (?, ?, ?, ?, ?)
      `,
      [
        "UNIT",
        unitId,
        "CREATE",
        `Unit baru dibuat: ${name} (${normalizedCode})`,
        created_by,
      ]
    );

    return NextResponse.json({
      success: true,
      message: "Unit berhasil dibuat",
    });

  } catch (err: any) {
    console.error("POST /units error:", err);

    return NextResponse.json(
      {
        success: false,
        message: "Gagal membuat unit",
        error: err?.message,
      },
      { status: 500 }
    );
  }
}