// =======================================================
// FILE:
// app/api/sto/route.ts
// =======================================================
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 page = Number(searchParams.get("page") || 1);
    const limit = 10;
    const offset = (page - 1) * limit;

    const status = searchParams.get("status");
    const keyword = searchParams.get("keyword");

    let where = "WHERE 1=1";
    const params: any[] = [];

    if (status) {
      where += " AND sto.status = ?";
      params.push(status);
    }

    if (keyword) {
      where += " AND sto.sto_number LIKE ?";
      params.push(`%${keyword}%`);
    }

    const [countRows]: any = await db.query(
      `
      SELECT COUNT(*) total
      FROM stock_transfer_orders sto
      ${where}
      `,
      params
    );

    const total = countRows[0].total;

    const [rows]: any = await db.query(
      `
      SELECT
        sto.*,

        f.name as from_location_name,
        t.name as to_location_name,

        u.id as created_by_id,
        u.name as created_by_name,
        u.email as created_by_email,
        u.role as created_by_role,

        COUNT(si.id) as total_items

      FROM stock_transfer_orders sto

      JOIN locations f ON f.id = sto.from_location_id
      JOIN locations t ON t.id = sto.to_location_id

      LEFT JOIN users u ON u.id = sto.created_by
      LEFT JOIN stock_transfer_order_items si ON si.sto_id = sto.id

      ${where}

      GROUP BY sto.id
      ORDER BY sto.created_at DESC
      LIMIT ? OFFSET ?
      `,
      [...params, limit, offset]
    );

    return NextResponse.json({
      data: rows,
      pagination: {
        total,
        page,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (err: any) {
    return NextResponse.json(
      { message: err.message },
      { status: 500 }
    );
  }
}

export async function POST(req: Request) {
  try {
    const session = await getServerSession(authOptions);

    const userId = session?.user?.id;

    if (!userId) {
      return NextResponse.json(
        { message: "Unauthorized" },
        { status: 401 }
      );
    }

    const body = await req.json();

    const {
      from_location_id,
      to_location_id,
      remarks,
    } = body;

    if (!from_location_id || !to_location_id) {
      return NextResponse.json({
        message: "Gudang wajib dipilih",
      });
    }

    if (from_location_id == to_location_id) {
      return NextResponse.json({
        message: "Gudang asal dan tujuan tidak boleh sama",
      });
    }

    const stoNumber = "STO-" + Date.now();
    // CreatedAt GMT + 7
    // const createdAtWIB = new Date(
    //     new Date().getTime() + 7 * 60 * 60 * 1000
    // );
    const [result]: any = await db.query(
      `
      INSERT INTO stock_transfer_orders
      (
        sto_number,
        from_location_id,
        to_location_id,
        remarks,
        status,
        created_by
      )
      VALUES (?, ?, ?, ?, 'DRAFT', ?)
      `,
      [
        stoNumber,
        from_location_id,
        to_location_id,
        remarks,
        userId,
      ]
    );
    // createdAtWIB,

    /* =======================================================
       🔥 ACTIVITY LOG (ADDED)
    ======================================================= */
    await db.query(
      `
      INSERT INTO activity_logs
      (
        entity,
        entity_id,
        action,
        description,
        created_by
      )
      VALUES (?, ?, ?, ?, ?)
      `,
      [
        "STO",
        result.insertId,
        "CREATE",
        `Create STO ${stoNumber} from ${from_location_id} to ${to_location_id}`,
        userId,
      ]
    );
    // createdAtWIB,

    return NextResponse.json({
      success: true,
      id: result.insertId,
    });

  } catch (err: any) {
    return NextResponse.json(
      { message: err.message },
      { status: 500 }
    );
  }
}