import { and, asc, eq, or } from "drizzle-orm";
import { db } from "@/db";
import { customers, products, territories } from "@/db/schema";
import type { SessionUser } from "@/lib/auth";
import { scopeFilter } from "@/lib/rbac";
import type { CustomerOption, ProductOption } from "./moi/order-form";

/**
 * Khách hàng và sản phẩm để chọn khi lên/sửa đơn. Khách chỉ trong phạm vi người lập đơn (NVKD: khách mình; quản lý: nhánh mình);
 * khi SỬA đơn, khách hiện tại của đơn luôn có trong danh sách dù đã chuyển người phụ trách — nếu thiếu, ô chọn trống và không lưu được.
 * Kèm thông tin xuất hoá đơn (MST, địa chỉ, người đại diện...) và người nhận hàng mặc định để hiển thị/điền sẵn trong form.
 */
export async function loadOrderFormOptions(session: SessionUser, currentCustomerId?: string) {
  const scope = await scopeFilter(session, {
    tenantId: customers.tenantId,
    ownerId: customers.ownerId,
    territoryId: customers.territoryId,
  });

  const [customerRows, productRows] = await Promise.all([
    db
      .select({
        id: customers.id,
        code: customers.code,
        orgName: customers.orgName,
        contactName: customers.contactName,
        taxCode: customers.taxCode,
        phone: customers.phone,
        email: customers.email,
        address: customers.address,
        ward: customers.ward,
        receiverName: customers.receiverName,
        receiverPhone: customers.receiverPhone,
        receiverAddress: customers.receiverAddress,
        territoryName: territories.name,
      })
      .from(customers)
      .leftJoin(territories, eq(customers.territoryId, territories.id))
      .where(
        and(
          eq(customers.tenantId, session.tenantId),
          currentCustomerId ? or(and(scope, eq(customers.isActive, true)), eq(customers.id, currentCustomerId)) : and(scope, eq(customers.isActive, true)),
        ),
      )
      .orderBy(asc(customers.orgName)),
    db
      .select({
        id: products.id,
        code: products.code,
        name: products.name,
        unit: products.unit,
        volume: products.volume,
        unitPrice: products.unitPrice,
        discountPercent: products.discountPercent,
      })
      .from(products)
      .where(and(eq(products.tenantId, session.tenantId), eq(products.isActive, true)))
      .orderBy(asc(products.code)),
  ]);

  const customerOptions: CustomerOption[] = customerRows.map((c) => ({
    id: c.id,
    code: c.code,
    orgName: c.orgName,
    territoryName: c.territoryName,
    contactName: c.contactName,
    taxCode: c.taxCode,
    phone: c.phone,
    email: c.email,
    address: [c.address, c.ward, c.territoryName].filter(Boolean).join(", ") || null,
    receiverName: c.receiverName,
    receiverPhone: c.receiverPhone,
    receiverAddress: c.receiverAddress,
  }));
  const productOptions: ProductOption[] = productRows.map((p) => ({
    id: p.id,
    code: p.code,
    name: p.name,
    unit: p.unit,
    volume: p.volume,
    unitPrice: Number(p.unitPrice),
    discountPercent: Number(p.discountPercent),
  }));
  return { customers: customerOptions, products: productOptions };
}
