"use server";

import { auth } from "@/auth";
import { db } from "@/lib/db";
import { hasPermission } from "@/lib/permissions";
import { buildCompanyAssetKey, uploadBuffer } from "@/lib/storage";
import { z } from "zod";
import { revalidatePath } from "next/cache";

type ActionResult = { ok: true } | { error: string };

// Branding assets (logo + stamp) shown on exported POs.
const ASSET_MIME: Record<string, string> = {
  "image/png": "png",
  "image/jpeg": "jpg",
  "image/jpg": "jpg",
  "image/webp": "webp",
};
const ASSET_MAX_BYTES = 4 * 1024 * 1024; // 4 MB — banners/seals can be larger than signatures

const companySchema = z.object({
  name:           z.string().min(1, "Company name is required"),
  code:           z.string().min(1, "Company code is required").max(10, "Code must be ≤ 10 characters").regex(/^[A-Z0-9]+$/i, "Code must be letters/numbers only").optional(),
  gstNumber:      z.string().optional(),
  address:        z.string().optional(),
  telephone:      z.string().optional(),
  mobile:         z.string().optional(),
  email:          z.string().email("Invalid email").optional().or(z.literal("")),
  invoiceEmail:   z.string().email("Invalid invoice email").optional().or(z.literal("")),
  invoiceAddress: z.string().optional(),
});

export async function createCompany(formData: FormData): Promise<{ ok: true; id: string } | { error: string }> {
  const session = await auth();
  if (!session?.user || !hasPermission(session.user.role, "manage_vessels_accounts")) {
    return { error: "Unauthorized" };
  }

  const parsed = companySchema.safeParse({
    name:           formData.get("name"),
    code:           (formData.get("code") as string) || undefined,
    gstNumber:      (formData.get("gstNumber") as string) || undefined,
    address:        (formData.get("address") as string) || undefined,
    telephone:      (formData.get("telephone") as string) || undefined,
    mobile:         (formData.get("mobile") as string) || undefined,
    email:          (formData.get("email") as string) || undefined,
    invoiceEmail:   (formData.get("invoiceEmail") as string) || undefined,
    invoiceAddress: (formData.get("invoiceAddress") as string) || undefined,
  });
  if (!parsed.success) return { error: parsed.error.errors[0]?.message ?? "Validation failed" };

  const { name, code, gstNumber, address, telephone, mobile, email, invoiceEmail, invoiceAddress } = parsed.data;
  if (code) {
    const conflict = await db.company.findFirst({ where: { code: { equals: code, mode: "insensitive" } } });
    if (conflict) return { error: `Code "${code.toUpperCase()}" is already used by another company.` };
  }
  const created = await db.company.create({
    data: { name, code: code?.toUpperCase() ?? null, gstNumber: gstNumber ?? null, address: address ?? null, telephone: telephone ?? null, mobile: mobile ?? null, email: email || null, invoiceEmail: invoiceEmail || null, invoiceAddress: invoiceAddress ?? null },
  });
  revalidatePath("/admin/companies");
  return { ok: true, id: created.id };
}

export async function updateCompany(formData: FormData): Promise<ActionResult> {
  const session = await auth();
  if (!session?.user || !hasPermission(session.user.role, "manage_vessels_accounts")) {
    return { error: "Unauthorized" };
  }

  const id = formData.get("id") as string;
  if (!id) return { error: "Company ID is required" };

  const parsed = companySchema.safeParse({
    name:           formData.get("name"),
    code:           (formData.get("code") as string) || undefined,
    gstNumber:      (formData.get("gstNumber") as string) || undefined,
    address:        (formData.get("address") as string) || undefined,
    telephone:      (formData.get("telephone") as string) || undefined,
    mobile:         (formData.get("mobile") as string) || undefined,
    email:          (formData.get("email") as string) || undefined,
    invoiceEmail:   (formData.get("invoiceEmail") as string) || undefined,
    invoiceAddress: (formData.get("invoiceAddress") as string) || undefined,
  });
  if (!parsed.success) return { error: parsed.error.errors[0]?.message ?? "Validation failed" };

  const { name, code, gstNumber, address, telephone, mobile, email, invoiceEmail, invoiceAddress } = parsed.data;
  if (code) {
    const conflict = await db.company.findFirst({ where: { code: { equals: code, mode: "insensitive" }, id: { not: id } } });
    if (conflict) return { error: `Code "${code.toUpperCase()}" is already used by another company.` };
  }
  await db.company.update({
    where: { id },
    data: { name, code: code?.toUpperCase() ?? null, gstNumber: gstNumber ?? null, address: address ?? null, telephone: telephone ?? null, mobile: mobile ?? null, email: email || null, invoiceEmail: invoiceEmail || null, invoiceAddress: invoiceAddress ?? null },
  });
  revalidatePath("/admin/companies");
  return { ok: true };
}

export async function deleteCompany(id: string): Promise<ActionResult> {
  const session = await auth();
  if (!session?.user || !hasPermission(session.user.role, "manage_vessels_accounts")) return { error: "Unauthorized" };

  const inUse = await db.purchaseOrder.findFirst({ where: { companyId: id } });
  if (inUse) return { error: "Cannot delete: company is referenced in purchase orders." };

  await db.company.delete({ where: { id } });
  revalidatePath("/admin/companies");
  return { ok: true };
}

// ── Branding assets (logo + stamp) ──────────────────────────────────────────────

export async function uploadCompanyAsset(formData: FormData): Promise<ActionResult> {
  const session = await auth();
  if (!session?.user || !hasPermission(session.user.role, "manage_vessels_accounts")) {
    return { error: "Unauthorized" };
  }

  const companyId = formData.get("companyId") as string | null;
  const type = formData.get("type") as string | null;
  if (!companyId) return { error: "Company ID is required" };
  if (type !== "logo" && type !== "stamp") return { error: "Invalid asset type" };

  const company = await db.company.findUnique({ where: { id: companyId }, select: { id: true } });
  if (!company) return { error: "Company not found" };

  const file = formData.get("file") as File | null;
  if (!file || file.size === 0) return { error: "No file provided" };
  if (file.size > ASSET_MAX_BYTES) return { error: "Image must be under 4 MB" };

  const ext = ASSET_MIME[file.type];
  if (!ext) return { error: "Image must be a PNG, JPG, or WebP" };

  const key = buildCompanyAssetKey(companyId, type, ext);
  const buffer = Buffer.from(await file.arrayBuffer());
  await uploadBuffer(key, buffer, file.type);

  await db.company.update({
    where: { id: companyId },
    data: type === "logo" ? { logoKey: key } : { stampKey: key },
  });

  revalidatePath("/admin/companies");
  return { ok: true };
}

export async function removeCompanyAsset(companyId: string, type: "logo" | "stamp"): Promise<ActionResult> {
  const session = await auth();
  if (!session?.user || !hasPermission(session.user.role, "manage_vessels_accounts")) {
    return { error: "Unauthorized" };
  }
  if (type !== "logo" && type !== "stamp") return { error: "Invalid asset type" };

  await db.company.update({
    where: { id: companyId },
    data: type === "logo" ? { logoKey: null } : { stampKey: null },
  });

  revalidatePath("/admin/companies");
  return { ok: true };
}

export async function toggleCompanyActive(id: string): Promise<ActionResult> {
  const session = await auth();
  if (!session?.user || !hasPermission(session.user.role, "manage_vessels_accounts")) {
    return { error: "Unauthorized" };
  }
  const company = await db.company.findUnique({ where: { id }, select: { isActive: true } });
  if (!company) return { error: "Company not found" };
  await db.company.update({ where: { id }, data: { isActive: !company.isActive } });
  revalidatePath("/admin/companies");
  return { ok: true };
}
