import { z } from 'zod'

export const invoiceSettingsCurrencies = ['ILS', 'USD', 'EUR'] as const
export const lateFeeTypes = ['none', 'flat', 'percentage'] as const

export type InvoiceSettingsCurrency = (typeof invoiceSettingsCurrencies)[number]
export type LateFeeType = (typeof lateFeeTypes)[number]
export type InvoiceTaskStatusTriggerInvoiceType = 'draft' | 'sent'

export interface InvoiceTaskStatusTrigger {
  enabled: boolean
  status_id: string
  invoice_type: InvoiceTaskStatusTriggerInvoiceType
}

export interface InvoiceSettings {
  default_payment_terms_days: number
  default_tax_rate: number
  default_currency: InvoiceSettingsCurrency
  invoice_number_prefix: string
  issue_tax_invoices: boolean
  proforma_number_prefix: string
  late_fee_type: LateFeeType
  late_fee_amount: number | null
  late_fee_threshold_days: number | null
  invoice_footer_text: string | null
  invoice_show_payment_link: boolean
  business_type: string | null
  business_tax_id: string | null
  vat_registration_number: string | null
  logo_url: string | null
  auto_send_retainer_invoice?: boolean
  task_status_trigger?: InvoiceTaskStatusTrigger | null
}

export const INVOICE_SETTINGS_DEFAULTS = {
  default_payment_terms_days: 30,
  default_tax_rate: 0.18,
  default_currency: 'ILS',
  invoice_number_prefix: 'INV-',
  issue_tax_invoices: true,
  proforma_number_prefix: 'PROFORMA-',
  late_fee_type: 'none',
  late_fee_amount: null,
  late_fee_threshold_days: 30,
  invoice_footer_text: null,
  invoice_show_payment_link: true,
} as const satisfies Omit<
  InvoiceSettings,
  'business_type' | 'business_tax_id' | 'vat_registration_number' | 'logo_url'
>

export const updateInvoiceSettingsSchema = z
  .object({
    default_payment_terms_days: z.number().int().min(0).max(365).optional(),
    default_tax_rate: z.number().min(0).max(1).optional(),
    default_currency: z.enum(invoiceSettingsCurrencies).optional(),
    invoice_number_prefix: z.string().trim().min(1).max(16).optional(),
    issue_tax_invoices: z.boolean().optional(),
    proforma_number_prefix: z.string().trim().min(1).max(16).optional(),
    late_fee_type: z.enum(lateFeeTypes).optional(),
    late_fee_amount: z.number().positive().nullable().optional(),
    late_fee_threshold_days: z.number().int().min(0).max(365).nullable().optional(),
    invoice_footer_text: z.string().max(1000).nullable().optional(),
    invoice_show_payment_link: z.boolean().optional(),
  })
  .superRefine((value, ctx) => {
    const lateFeeType = value.late_fee_type
    if (lateFeeType === 'flat' || lateFeeType === 'percentage') {
      if (typeof value.late_fee_amount !== 'number' || value.late_fee_amount <= 0) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          message: 'late_fee_amount required and > 0 when late_fee_type is flat or percentage',
          path: ['late_fee_amount'],
        })
      }
    }
  })

export type UpdateInvoiceSettingsInput = z.infer<typeof updateInvoiceSettingsSchema>
