"use server";

import { revalidatePath } from "next/cache";
import { and, eq } from "drizzle-orm";
import { db } from "@/db";
import { forecasts } from "@/db/schema";
import { requireSession } from "@/lib/auth";
import { canEditCatalog } from "@/lib/rbac";

/**
 * Ghi đè số lượng dự báo bằng con số người dùng tự quyết.
 *
 * Cột `forecastQty` do máy tính giữ nguyên để đối chiếu về sau — muốn biết dự báo
 * của hệ thống lệch bao nhiêu so với quyết định thực tế thì phải còn cả hai con số.
 * Bỏ trống ô nhập nghĩa là quay lại dùng số máy tính.
 */
export async function adjustForecastAction(formData: FormData) {
  const session = await requireSession();
  if (!canEditCatalog(session)) throw new Error("Bạn không có quyền chỉnh dự báo.");

  const id = String(formData.get("id"));
  const raw = String(formData.get("adjustedQty") ?? "").trim();

  const adjustedQty = raw === "" ? null : Number(raw);
  if (adjustedQty != null && (!Number.isFinite(adjustedQty) || adjustedQty < 0)) {
    throw new Error("Số lượng điều chỉnh không hợp lệ.");
  }

  await db
    .update(forecasts)
    .set({ adjustedQty: adjustedQty == null ? null : Math.round(adjustedQty) })
    .where(and(eq(forecasts.tenantId, session.tenantId), eq(forecasts.id, id)));

  revalidatePath("/phan-tich");
}
