import { z } from 'zod';
import { baseListQuerySchema } from '@/lib/api/list-query';
import { optionalCountryIsoSchema, optionalSubdivisionIsoSchema } from '@/lib/validators/i18n';

// react-hook-form posts empty strings for unfilled inputs; treat those
// as "not provided" before `.email()` / `.date()` validators fire.
const emptyToUndef = (v: unknown) => (v === '' ? undefined : v);

export const createCompanySchema = z.object({
  name: z.string().min(1).max(200),
  legalName: z.string().optional(),
  taxId: z.string().optional(),
  registrationNumber: z.string().optional(),
  /** ISO-3166-1 alpha-2 country of incorporation. */
  incorporationCountryIso: optionalCountryIsoSchema.optional(),
  /** ISO 3166-2 state/province of incorporation. */
  incorporationSubdivisionIso: optionalSubdivisionIsoSchema.optional(),
  incorporationDate: z.preprocess(emptyToUndef, z.coerce.date().optional()),
  status: z.enum(['active', 'dissolved']).optional().default('active'),
  billingEmail: z.preprocess(emptyToUndef, z.string().email().optional()),
  notes: z.string().optional(),
  tagIds: z.array(z.string()).optional().default([]),
});

export const updateCompanySchema = createCompanySchema.partial().omit({ tagIds: true });

export const listCompaniesSchema = baseListQuerySchema.extend({
  status: z.enum(['active', 'dissolved']).optional(),
  search: z.string().optional(),
});

export type CreateCompanyInput = z.infer<typeof createCompanySchema>;
export type UpdateCompanyInput = z.infer<typeof updateCompanySchema>;
export type ListCompaniesInput = z.infer<typeof listCompaniesSchema>;
