/**
 * Contract (Fulfillment-Rahmenvertrag) form logic — companion to
 * useOfferQuote.ts. The client owns the parameters; the server renders the
 * legal text (server/utils/offers/contractTexts.ts) with these values.
 */

const cNum = (v: any): number => {
  const n = Number(v)
  return Number.isFinite(n) ? n : 0
}

const contractFirstOfNextMonth = (): string => {
  const d = new Date()
  const next = new Date(d.getFullYear(), d.getMonth() + 1, 1)
  const mm = String(next.getMonth() + 1).padStart(2, '0')
  return `${next.getFullYear()}-${mm}-01`
}

/**
 * Build the contract form model from a host-page prefill
 * ({ source, recordId, recordUu?, company, contactName, email, phone, storageQty? }).
 */
export const createContractForm = (prefill: any = {}) => {
  const sq = prefill?.storageQty || {}
  return {
    source: prefill?.source || 'partner',
    recordId: cNum(prefill?.recordId),
    recordUu: prefill?.recordUu || '',
    language: 'de',
    customer: {
      company: prefill?.company || '',
      contactName: prefill?.contactName || '',
      signerPosition: 'Geschäftsführer',
      email: prefill?.email || '',
      phone: prefill?.phone || '',
      street: '',
      zip: '',
      city: '',
      country: 'Deutschland',
      ustId: ''
    },
    assumptions: {
      businessModel: 'B2C',
      plannedStart: contractFirstOfNextMonth(),
      shopSystem: '',
      avgPicksPerOrder: 1.5,
      ordersPerMonth: 500,
      skuCount: 100,
      storage: {
        shelfSmallQty: cNum(sq.shelfSmall),
        shelfLargeQty: cNum(sq.shelfLarge),
        palletQty: cNum(sq.pallet),
        volumeM3: 0
      }
    },
    contract: {
      offerDate: new Date().toISOString().slice(0, 10),
      noticeMonths: 3,
      priceNoticeMonths: 2,
      objectionWeeks: 6,
      curePeriodDays: 3,
      cutoffTime: '14:00',
      shrinkagePct: 1,
      paymentMethod: 'sepa',
      marketingVariant: 'consent',
      includeExpress: false,
      customClauses: []
    },
    email: {
      to: prefill?.email || '',
      cc: '',
      subject: '',
      message: ''
    }
  }
}

/** Assemble the payload for the contract preview/send server routes. */
export const buildContractPayload = (form: any, withEmail = false) => {
  const payload: any = {
    docType: 'contract',
    source: form.source,
    recordId: form.recordId,
    recordUu: form.recordUu || undefined,
    customer: { ...form.customer, country: form.customer.country || 'Deutschland' },
    assumptions: JSON.parse(JSON.stringify(form.assumptions)),
    contract: JSON.parse(JSON.stringify(form.contract)),
    meta: {
      language: form.language === 'en' ? 'en' : 'de',
      date: new Date().toISOString().slice(0, 10)
    }
  }
  if (withEmail) {
    payload.email = {
      to: form.email.to.trim(),
      cc: form.email.cc.trim(),
      subject: form.email.subject,
      message: form.email.message
    }
  }
  return payload
}

/** Language-dependent email defaults for sending the contract. */
export const contractEmailDefaults = (language: string, contactName: string, company: string) => {
  if (language === 'en') {
    return {
      subject: `Your fulfillment agreement with LogYou – ${company}`,
      message: `Dear ${contactName || 'Sir or Madam'},\n\nthank you for choosing LogYou fulfillment.\n\nPlease find attached our fulfillment service agreement as PDF. Kindly review it and return a signed copy to us.\nIf you have any questions, we are happy to help at any time.\n\nBest regards\nYour LogYou team`
    }
  }
  return {
    subject: `Ihr Fulfillment-Vertrag mit LogYou – ${company}`,
    message: `Guten Tag ${contactName || 'Damen und Herren'},\n\nvielen Dank für Ihr Vertrauen in LogYou Fulfillment.\n\nanbei erhalten Sie unseren Fulfillment-Rahmenvertrag als PDF. Bitte prüfen Sie den Vertrag und senden Sie uns ein unterschriebenes Exemplar zurück.\nBei Fragen stehen wir Ihnen jederzeit gerne zur Verfügung.\n\nMit freundlichen Grüßen\nIhr LogYou Team`
  }
}
