"use server";

import { revalidatePath } from "next/cache";
import { requireSession } from "@/lib/auth";
import { canManageSettings } from "@/lib/rbac";
import { db } from "@/db";
import { auditLogs } from "@/db/schema";
import {
  previewImport,
  runImport,
  type ImportKind,
  type ImportPreview,
  type ImportResult,
} from "@/lib/import";

const KINDS: ImportKind[] = ["san-pham", "khach-hang", "don-hang"];

export type ImportState = {
  preview?: ImportPreview;
  result?: ImportResult;
  error?: string;
  kind?: ImportKind;
};

/** Chỉ đọc và kiểm tra file, chưa ghi gì vào cơ sở dữ liệu. */
export async function previewAction(_prev: ImportState, formData: FormData): Promise<ImportState> {
  const session = await requireSession();
  if (!canManageSettings(session)) return { error: "Nhập dữ liệu hàng loạt chỉ dành cho Ban giám đốc." };

  const kind = String(formData.get("kind")) as ImportKind;
  if (!KINDS.includes(kind)) return { error: "Loại dữ liệu không hợp lệ." };

  const file = formData.get("file");
  if (!(file instanceof File) || file.size === 0) {
    return { kind, error: "Vui lòng chọn file Excel (.xlsx)." };
  }

  try {
    const preview = await previewImport(session.tenantId, kind, await file.arrayBuffer());
    return { kind, preview };
  } catch (error) {
    return { kind, error: error instanceof Error ? error.message : "Không đọc được file Excel." };
  }
}

/** Ghi dữ liệu sau khi người dùng đã xem trước và xác nhận. */
export async function confirmImportAction(
  _prev: ImportState,
  formData: FormData,
): Promise<ImportState> {
  const session = await requireSession();
  if (!canManageSettings(session)) return { error: "Nhập dữ liệu hàng loạt chỉ dành cho Ban giám đốc." };

  const kind = String(formData.get("kind")) as ImportKind;
  if (!KINDS.includes(kind)) return { error: "Loại dữ liệu không hợp lệ." };

  const file = formData.get("file");
  if (!(file instanceof File) || file.size === 0) {
    return { kind, error: "Vui lòng chọn lại file để xác nhận nhập." };
  }

  try {
    const result = await runImport(session.tenantId, session.userId, kind, await file.arrayBuffer());

    await db.insert(auditLogs).values({
      tenantId: session.tenantId,
      userId: session.userId,
      action: "IMPORT",
      entityType: kind,
      payload: { inserted: result.inserted, updated: result.updated, fileName: file.name },
    });

    revalidatePath("/danh-muc");
    revalidatePath("/khach-hang");
    revalidatePath("/don-hang");
    return { kind, result };
  } catch (error) {
    return { kind, error: error instanceof Error ? error.message : "Nhập dữ liệu thất bại." };
  }
}
