import type { BaseEntity } from "../common";

export type FileUploadEntity =
  | "customer"
  | "booking"
  | "consignment"
  | "shipment"
  | "invoice"
  | "train"
  | "other";

export interface IFileUploadField extends BaseEntity {
  settingId: string;
  /** Stable identifier used by the API / object storage. */
  fileKey: string;
  /** Human-readable label rendered above the input. */
  fileLabel: string;
  helpText?: string | null;
  isRequired: boolean;
  isMultiple: boolean;
  /** Upper bound on file count when isMultiple is true. */
  maxFiles: number;
  allowedExtensions: string[];
  maxSizeMb: number;
  order: number;
}

export interface IFileUploadSetting extends BaseEntity {
  /** Stable code referenced from forms (snake_case). */
  code: string;
  /** Display label for admins. */
  label: string;
  description?: string | null;
  entity: FileUploadEntity;
  fields: IFileUploadField[];
}

/* ------------------------------------------------------------------ *
 *  Wire DTOs (shared between API and frontend)
 * ------------------------------------------------------------------ */

export interface CreateFileUploadFieldDto {
  fileKey: string;
  fileLabel: string;
  helpText?: string;
  isRequired: boolean;
  isMultiple: boolean;
  maxFiles: number;
  allowedExtensions: string[];
  maxSizeMb: number;
  order?: number;
}

export type UpdateFileUploadFieldDto = Partial<CreateFileUploadFieldDto>;

export interface CreateFileUploadSettingDto {
  code: string;
  label: string;
  description?: string;
  entity: FileUploadEntity;
  fields?: CreateFileUploadFieldDto[];
}

export type UpdateFileUploadSettingDto = Partial<
  Omit<CreateFileUploadSettingDto, "fields">
>;

/* ------------------------------------------------------------------ *
 *  Helpers — encode the required × multiple matrix.
 *
 *    required | multiple |  min |  max
 *    ---------|----------|------|--------------
 *    no       | no       |  0   |  1
 *    yes      | no       |  1   |  1
 *    no       | yes      |  0   | field.maxFiles
 *    yes      | yes      |  1   | field.maxFiles
 * ------------------------------------------------------------------ */

export function getMinFiles(
  field: Pick<IFileUploadField, "isRequired">,
): number {
  return field.isRequired ? 1 : 0;
}

export function getEffectiveMaxFiles(
  field: Pick<IFileUploadField, "isMultiple" | "maxFiles">,
): number {
  return field.isMultiple ? Math.max(1, field.maxFiles) : 1;
}
