import * as Yup from 'yup';
import {
  SalesOrderProductFormValues,
  SalesOrderProductSchema,
} from '@/components/pages/marketing/form/repeater/sales-order/SalesOrderProduct.schema';
import {
  DeliveryOrderProductFormValues,
  DeliveryOrderProductSchema,
} from '@/components/pages/marketing/form/repeater/delivery-order/DeliverOrderProduct.schema';

type MarketingSchemaType = {
  customer_id: number | undefined;
  sales_person_id: number | undefined;
  sales_person:
    | {
        value: number;
        label: string;
      }
    | undefined
    | null;
  customer:
    | {
        value: number;
        label: string;
      }
    | undefined
    | null;
  so_date: string | undefined;
  notes: string | undefined;
};

type SalesOrderSchemaType = MarketingSchemaType & {
  sales_order: SalesOrderProductFormValues[];
};

type DeliveryOrderSchemaType = {
  delivery_order: DeliveryOrderProductFormValues[];
};

export const SalesOrderSchema: Yup.ObjectSchema<SalesOrderSchemaType> =
  Yup.object({
    customer_id: Yup.number().required('Customer wajib diisi!'),
    sales_person_id: Yup.number().required('Sales wajib diisi!'),
    sales_person: Yup.object({
      value: Yup.number().required(),
      label: Yup.string().required(),
    }).nullable(),
    customer: Yup.object({
      value: Yup.number().required(),
      label: Yup.string().required(),
    }).nullable(),
    so_date: Yup.string().required('Tanggal wajib diisi!'),
    notes: Yup.string().required('Catatan wajib diisi!'),
    sales_order: Yup.array()
      .of(SalesOrderProductSchema)
      .min(1, 'Produk wajib diisi!')
      .required('Produk wajib diisi!'),
  });

export const DeliveryOrderSchema: Yup.ObjectSchema<DeliveryOrderSchemaType> =
  Yup.object({
    delivery_order: Yup.array()
      .min(1, 'Pengiriman wajib diisi!')
      .required('Pengiriman wajib diisi!')
      .test(
        'at-least-one-valid-row',
        'Minimal ada satu baris pengiriman yang valid!',
        function (items) {
          if (!items || items.length === 0) return false;

          // VALIDASI: minimal 1 item valid full
          const itemSchema = DeliveryOrderProductSchema;

          const hasValidItem = items.some((item) => {
            if (!item) return false;
            return itemSchema.isValidSync(item, { abortEarly: true });
          });

          return hasValidItem;
        }
      ),
  });

export const UpdateSalesOrderSchema = SalesOrderSchema;

export type SalesOrderFormValues = Yup.InferType<typeof SalesOrderSchema>;

export type DeliveryOrderFormValues = Yup.InferType<typeof DeliveryOrderSchema>;
