import { NextResponse } from "next/server";
import { db } from "../../../lib/db";
import { getServerSession } from "next-auth";


export async function POST(req: Request) {
  try {
    const session = await getServerSession();

    if (!session?.user?.id) {
      return NextResponse.json(
        { message: "Unauthorized" },
        { status: 401 }
      );
    }

    const body = await req.json();

    const {
      location_id,
      zone_id,
      category_id,
      notes,
      schedule_date,
    } = body;

    if (!location_id) {
      return NextResponse.json(
        { message: "Warehouse is required" },
        { status: 400 }
      );
    }

    // =========================
    // CREATE STOCK OPNAME
    // =========================
    const [result]: any = await db.query(
      `
      INSERT INTO stock_opnames (
        location_id,
        category_id,
        notes,
        schedule_date,
        status,
        created_by,
        created_at
      ) VALUES (?, ?, ?, ?, 'DRAFT', ?, NOW())
      `,
      [
        location_id,
        category_id || null,
        notes || null,
        schedule_date || null,
        session.user.id,
      ]
    );

    const stockOpnameId = result.insertId;

    // =========================
    // ACTIVITY LOG (IMPORTANT)
    // =========================
    await db.query(
      `
      INSERT INTO activity_logs (
        entity,
        entity_id,
        action,
        description,
        created_by,
        created_at
      ) VALUES (?, ?, ?, ?, ?, NOW())
      `,
      [
        "STOCK_OPNAME",
        stockOpnameId,
        "CREATE",
        `Create stock opname for location_id=${location_id} status=DRAFT`,
        session.user.id,
      ]
    );

    return NextResponse.json({
      message: "Stock opname created",
      id: stockOpnameId,
    });
  } catch (error) {
    console.error("[STOCK OPNAME CREATE ERROR]", error);

    return NextResponse.json(
      { message: "Failed create stock opname" },
      { status: 500 }
    );
  }
}