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,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;

    /* ================= ITEM + RELATION ================= */
    const [items]: any = await db.query(
      `
      SELECT 
        i.*,
        c.name as category,

        /* UNIT */
        u.name as unit_name,
        u.code as unit_code,
        u.symbol as unit_symbol,
        u.category as unit_category,

        /* SUPPLIER (HANYA NAME) */
        s.id as supplier_id,
        s.name as supplier_name

      FROM items i
      LEFT JOIN categories c ON c.id = i.category_id
      LEFT JOIN units u ON u.code = i.units
      LEFT JOIN suppliers s ON s.id = i.supplier_id

      WHERE i.id = ?
      LIMIT 1
      `,
      [id]
    );

    if (items.length === 0) {
      return NextResponse.json(
        { message: "Item tidak ditemukan" },
        { status: 404 }
      );
    }

    const item = items[0];

    /* ================= BARCODES ================= */
    const [barcodes]: any = await db.query(
      `SELECT * FROM item_barcodes WHERE item_id = ?`,
      [id]
    );

    /* ================= DIMENSIONS ================= */
    const [dimension]: any = await db.query(
      `SELECT * FROM item_dimensions WHERE item_id = ? LIMIT 1`,
      [id]
    );

    /* ================= PRICING ================= */
    const [pricing]: any = await db.query(
      `SELECT * FROM item_pricing WHERE item_id = ?`,
      [id]
    );

    /* ================= TAX ================= */
    const [tax]: any = await db.query(
      `SELECT * FROM item_taxes WHERE item_id = ? LIMIT 1`,
      [id]
    );

    /* ================= CONVERSIONS ================= */
    const [conversions]: any = await db.query(
      `SELECT * FROM item_unit_conversions WHERE item_id = ?`,
      [id]
    );

    return NextResponse.json({
      item,
      barcodes,
      dimension: dimension[0] || null,
      pricing,
      tax: tax[0] || null,
      conversions,
    });
  } catch (err: any) {
    return NextResponse.json(
      { message: "Failed load detail", error: err?.message },
      { status: 500 }
    );
  }
}


export async function PUT(req: Request, context: any) {
  try {
    const { id } = await context.params;

    if (!id) {
      return NextResponse.json(
        { message: "ID tidak valid" },
        { status: 400 }
      );
    }

    const body = await req.json();

    let {
      sku,
      name,
      description,
      category_id,
      supplier_id,   // ✅ ADD INI
      unit,
      barcode,
      is_active = true,
    } = body;

    sku = sku?.toUpperCase();

    if (!sku || !name || !unit) {
      return NextResponse.json(
        { message: "SKU, Name, Unit wajib diisi" },
        { status: 400 }
      );
    }

    /* ================= SESSION USER (ADDED) ================= */
    const session = await getServerSession(authOptions);
    const created_by = session?.user?.id ? Number(session.user.id) : null;

    /* ================= CHECK DUPLICATE SKU ================= */
    const [dup]: any = await db.query(
      `SELECT id FROM items WHERE sku = ? AND id != ? LIMIT 1`,
      [sku, id]
    );

    if (dup.length > 0) {
      return NextResponse.json(
        { message: "SKU sudah digunakan" },
        { status: 400 }
      );
    }

    /* ================= UPDATE ITEM ================= */
    await db.query(
      `
      UPDATE items
      SET 
        sku = ?, 
        name = ?, 
        description = ?, 
        category_id = ?, 
        supplier_id = ?,   
        unit = ?, 
        is_active = ?
      WHERE id = ?
      `,
      [
        sku,
        name,
        description,
        category_id || null,
        supplier_id || null,
        unit,
        is_active,
        id
      ]
    );

    /* ================= HANDLE BARCODE ================= */
    if (barcode) {
      const [existing]: any = await db.query(
        `SELECT id FROM item_barcodes WHERE item_id = ? AND is_primary = 1 LIMIT 1`,
        [id]
      );

      if (existing.length > 0) {
        await db.query(
          `UPDATE item_barcodes SET barcode = ? WHERE item_id = ? AND is_primary = 1`,
          [barcode, id]
        );
      } else {
        await db.query(
          `INSERT INTO item_barcodes (item_id, barcode, is_primary) VALUES (?, ?, 1)`,
          [id, barcode]
        );
      }
    }

    /* ================= ACTIVITY LOG (FIXED) ================= */
    await db.query(
      `
      INSERT INTO activity_logs (
        entity,
        entity_id,
        action,
        description,
        created_by
      ) VALUES (?, ?, ?, ?, ?)
      `,
      [
        "ITEM",
        id,
        "UPDATE",
        `Item diupdate: ${sku} - ${name}`,
        created_by,
      ]
    );

    return NextResponse.json({
      message: "Item berhasil diupdate",
    });

  } catch (err: any) {
    console.error("ERROR UPDATE ITEM:", err);

    return NextResponse.json(
      { message: "Gagal update item", error: err?.message },
      { status: 500 }
    );
  }
}


export async function DELETE(req: Request, context: any) {
  const conn = await db.getConnection();

  try {
    const { params } = context;
    const { id } = await params;

    if (!id) {
      return NextResponse.json(
        { message: "ID tidak valid" },
        { status: 400 }
      );
    }

    /* ================= SESSION USER (ADDED) ================= */
    const session = await getServerSession(authOptions);
    const created_by = session?.user?.id ? Number(session.user.id) : null;

    await conn.beginTransaction();

    /* ================= CHECK EXIST ================= */
    const [rows]: any = await conn.query(
      `SELECT sku, name FROM items WHERE id = ?`,
      [id]
    );

    if (rows.length === 0) {
      await conn.rollback();
      return NextResponse.json(
        { message: "Item tidak ditemukan" },
        { status: 404 }
      );
    }

    const item = rows[0];

    /* ================= CHECK DEPENDENCY ================= */
    const [[inventory]]: any = await conn.query(
      `SELECT COUNT(*) as total FROM inventories WHERE item_id = ?`,
      [id]
    );

    const [[movements]]: any = await conn.query(
      `SELECT COUNT(*) as total FROM stock_movements WHERE item_id = ?`,
      [id]
    );

    const isUsed = inventory.total > 0 || movements.total > 0;

    if (isUsed) {
      await conn.rollback();
      return NextResponse.json(
        {
          message:
            "Item tidak bisa dihapus karena sudah dipakai di inventory / transaksi",
        },
        { status: 400 }
      );
    }

    /* ================= DELETE CHILD TABLES ================= */
    await conn.query(`DELETE FROM item_barcodes WHERE item_id = ?`, [id]);
    await conn.query(`DELETE FROM item_dimensions WHERE item_id = ?`, [id]);
    await conn.query(`DELETE FROM item_pricing WHERE item_id = ?`, [id]);
    await conn.query(`DELETE FROM item_unit_conversions WHERE item_id = ?`, [id]);
    await conn.query(`DELETE FROM item_taxes WHERE item_id = ?`, [id]);

    /* ================= DELETE MAIN ================= */
    await conn.query(`DELETE FROM items WHERE id = ?`, [id]);

    /* ================= ACTIVITY LOG (FIXED) ================= */
    await conn.query(
      `
      INSERT INTO activity_logs (
        entity,
        entity_id,
        action,
        description,
        created_by
      ) VALUES (?, ?, ?, ?, ?)
      `,
      [
        "ITEM",
        id,
        "DELETE",
        `Item dihapus: ${item.sku} - ${item.name}`,
        created_by,
      ]
    );

    await conn.commit();

    return NextResponse.json({
      success: true,
      message: "Item berhasil dihapus permanen",
    });

  } catch (err: any) {
    await conn.rollback();

    console.error(err);

    return NextResponse.json(
      {
        message: "Gagal menghapus item",
        error: err?.message,
      },
      { status: 500 }
    );
  } finally {
    conn.release();
  }
}
