import { NextResponse } from "next/server";
import { db } from "../../lib/db";
import { getServerSession } from "next-auth";
import { authOptions } from "../auth/[...nextauth]/route";

/* ================= GET LIST GUDANG ================= */
export async function GET(req: Request) {
  const { searchParams } = new URL(req.url);

  const search = searchParams.get("search") || "";
  const type = searchParams.get("type") || "";
  const page = Number(searchParams.get("page") || 1);
  const limit = Number(searchParams.get("limit") || 10);

  const offset = (page - 1) * limit;

  let where = "WHERE 1=1";
  let params: any[] = [];

  if (search) {
    where += " AND (l.name LIKE ? OR l.code LIKE ?)";
    params.push(`%${search}%`, `%${search}%`);
  }

  if (type) {
    where += " AND l.type = ?";
    params.push(type);
  }

  /* ================= COUNT ================= */
  const [count]: any = await db.query(
    `
    SELECT COUNT(*) as total
    FROM locations l
    ${where}
    `,
    params
  );

  /* ================= DATA ================= */
  const [rows]: any = await db.query(
    `
    SELECT 
      l.id,
      l.code,
      l.name,
      l.type,
      l.address,

      COALESCE(SUM(i.quantity), 0) as total_items,
      COUNT(DISTINCT i.item_id) as total_sku

    FROM locations l

    LEFT JOIN inventories i 
      ON i.location_id = l.id

    ${where}

    GROUP BY l.id, l.code, l.name, l.type, l.address

    ORDER BY l.name ASC
    LIMIT ? OFFSET ?
    `,
    [...params, limit, offset]
  );

  return NextResponse.json({
    locations: rows,
    total: count[0].total,
  });
}

/* ================= CREATE GUDANG ================= */
export async function POST(req: Request) {
  const conn = await db.getConnection();

  try {
    const body = await req.json();

    const { code, name, type, address } = body;

    if (!code || !name) {
      return NextResponse.json(
        { message: "Code & Name wajib diisi" },
        { status: 400 }
      );
    }
    const session = await getServerSession(authOptions);
    const userId = session?.user?.id || null;

    await conn.beginTransaction();

    /* ================= INSERT LOCATION ================= */
    const [result]: any = await conn.query(
      `
      INSERT INTO locations (code, name, type, address)
      VALUES (?, ?, ?, ?)
      `,
      [code, name, type || "WAREHOUSE", address || null]
    );

    const locationId = result.insertId;

    /* ================= ACTIVITY LOG ================= */
    await conn.query(
      `
      INSERT INTO activity_logs (
        entity,
        entity_id,
        action,
        description,
        created_by
      ) VALUES (?, ?, ?, ?, ?)
      `,
      [
        "LOCATION",
        locationId,
        "CREATE",
        `Tambah gudang:
      name: ${name}
      code: ${code}
      type: ${type || "WAREHOUSE"}
      address: ${address || "-"}`,
        userId,
      ]
    );

    await conn.commit();

    return NextResponse.json({
      message: "Gudang berhasil ditambahkan",
    });
  } catch (err: any) {
    await conn.rollback();

    console.error(err);

    return NextResponse.json(
      {
        message: "Server error",
        error: err.message,
      },
      { status: 500 }
    );
  } finally {
    conn.release();
  }
}