/**
 * SEPA direct debit mandate (SEPA-Lastschriftmandat) — wording and mandatory
 * content, DE (default) + EN.
 *
 * Mandatory content of a mandate (Deutsche Kreditwirtschaft / EPC rulebook):
 *   - heading "SEPA-Lastschriftmandat" + scheme (CORE = Basislastschrift | B2B = Firmenlastschrift)
 *   - creditor: name, address, Gläubiger-Identifikationsnummer (creditor identifier)
 *   - Mandatsreferenz (unique per mandate, max 35 chars, assigned by the creditor)
 *   - payment type: recurring (wiederkehrend) or one-off (einmalig)
 *   - the authorisation text (A: creditor may collect, B: bank shall honour) and,
 *     for CORE, the 8-week refund notice; for B2B the "no refund" notice
 *   - debtor: name (account holder), address, IBAN (BIC optional within SEPA)
 *   - place, date, signature of the account holder
 * The pre-notification (Vorabankündigung, default 14 days → often shortened to
 * 1 day by agreement) is stated as an information line.
 */
export type SepaScheme = 'CORE' | 'B2B'
export type SepaLang = 'de' | 'en'

export interface SepaCreditor {
  name: string
  street: string
  zipCity: string
  country: string
  creditorId: string
  /** Pre-notification lead time in days (info line). */
  prenotificationDays: number
}

export interface SepaMandateData {
  scheme: SepaScheme
  recurring: boolean
  mandateReference: string
  creditor: SepaCreditor
  /** Pre-filled debtor data (may be empty; the portal collects the rest). */
  debtor: {
    company?: string
    accountHolder?: string
    street?: string
    zipCity?: string
    country?: string
    iban?: string
    bic?: string
    bank?: string
  }
}

const T = {
  de: {
    title: 'SEPA-Lastschriftmandat',
    schemeCore: 'SEPA-Basislastschrift (CORE)',
    schemeB2B: 'SEPA-Firmenlastschrift (B2B)',
    creditor: 'Zahlungsempfänger (Gläubiger)',
    creditorId: 'Gläubiger-Identifikationsnummer',
    mandateRef: 'Mandatsreferenz',
    paymentType: 'Zahlungsart',
    recurring: 'Wiederkehrende Zahlungen',
    oneOff: 'Einmalige Zahlung',
    debtor: 'Zahlungspflichtiger (Kontoinhaber)',
    company: 'Firma',
    accountHolder: 'Kontoinhaber (Vor- und Nachname / Firma)',
    street: 'Straße und Hausnummer',
    zipCity: 'PLZ und Ort',
    country: 'Land',
    iban: 'IBAN',
    bic: 'BIC (optional innerhalb des SEPA-Raums)',
    bank: 'Kreditinstitut (Name)',
    placeDate: 'Ort, Datum',
    signature: 'Unterschrift des Kontoinhabers',
    authCore: (c: string) => `Ich ermächtige / Wir ermächtigen (A) ${c}, Zahlungen von meinem / unserem Konto mittels Lastschrift einzuziehen. Zugleich (B) weise ich mein / weisen wir unser Kreditinstitut an, die von ${c} auf mein / unser Konto gezogenen Lastschriften einzulösen.`,
    noticeCore: 'Hinweis: Ich kann / Wir können innerhalb von acht Wochen, beginnend mit dem Belastungsdatum, die Erstattung des belasteten Betrages verlangen. Es gelten dabei die mit meinem / unserem Kreditinstitut vereinbarten Bedingungen.',
    authB2B: (c: string) => `Ich ermächtige / Wir ermächtigen (A) ${c}, Zahlungen von meinem / unserem Konto mittels Lastschrift einzuziehen. Zugleich (B) weise ich mein / weisen wir unser Kreditinstitut an, die von ${c} auf mein / unser Konto gezogenen Lastschriften einzulösen.`,
    noticeB2B: 'Hinweis: Dieses Lastschriftmandat dient nur dem Einzug von Lastschriften, die auf Konten von Unternehmen gezogen werden. Ich bin / Wir sind nicht berechtigt, nach der erfolgten Einlösung eine Erstattung des belasteten Betrages zu verlangen. Ich bin / Wir sind berechtigt, mein / unser Kreditinstitut bis zum Fälligkeitstag anzuweisen, Lastschriften nicht einzulösen.',
    prenote: (d: number) => `Vorabankündigung (Pre-Notification): Der Zahlungsempfänger kündigt jede Lastschrift mindestens ${d} ${d === 1 ? 'Tag' : 'Tage'} vor Fälligkeit an (z. B. auf der Rechnung).`,
    footer: 'Das Mandat gilt für den Einzug der Entgelte aus dem Fulfillment-/Dienstleistungsverhältnis zwischen Zahlungsempfänger und Zahlungspflichtigem. Es kann jederzeit schriftlich widerrufen werden und erlischt, wenn 36 Monate lang keine Lastschrift eingezogen wurde.',
    fillHint: 'Bitte die grau hinterlegten Felder ausfüllen.'
  },
  en: {
    title: 'SEPA Direct Debit Mandate',
    schemeCore: 'SEPA Core Direct Debit (CORE)',
    schemeB2B: 'SEPA Business-to-Business Direct Debit (B2B)',
    creditor: 'Creditor (payee)',
    creditorId: 'Creditor identifier',
    mandateRef: 'Mandate reference',
    paymentType: 'Type of payment',
    recurring: 'Recurrent payment',
    oneOff: 'One-off payment',
    debtor: 'Debtor (account holder)',
    company: 'Company',
    accountHolder: 'Account holder (name / company)',
    street: 'Street and number',
    zipCity: 'Postal code and city',
    country: 'Country',
    iban: 'IBAN',
    bic: 'BIC (optional within SEPA)',
    bank: 'Bank (name)',
    placeDate: 'Place, date',
    signature: 'Signature of the account holder',
    authCore: (c: string) => `By signing this mandate form, you authorise (A) ${c} to send instructions to your bank to debit your account and (B) your bank to debit your account in accordance with the instructions from ${c}.`,
    noticeCore: 'Note: As part of your rights, you are entitled to a refund from your bank under the terms and conditions of your agreement with your bank. A refund must be claimed within eight weeks starting from the date on which your account was debited.',
    authB2B: (c: string) => `By signing this mandate form, you authorise (A) ${c} to send instructions to your bank to debit your account and (B) your bank to debit your account in accordance with the instructions from ${c}.`,
    noticeB2B: 'Note: This mandate is only intended for business-to-business transactions. You are not entitled to a refund from your bank after your account has been debited, but you are entitled to request your bank not to debit your account up until the day on which the payment is due.',
    prenote: (d: number) => `Pre-notification: the creditor announces each direct debit at least ${d} ${d === 1 ? 'day' : 'days'} before the due date (e.g. on the invoice).`,
    footer: 'This mandate covers the collection of fees arising from the fulfilment / service relationship between creditor and debtor. It may be revoked in writing at any time and lapses if no direct debit has been collected for 36 months.',
    fillHint: 'Please complete the shaded fields.'
  }
}

export const sepaTexts = (lang: SepaLang) => T[lang === 'en' ? 'en' : 'de']

/** Four unchecked declarations the account holder confirms in the portal (server-owned wording). */
export const sepaAcceptanceTexts = (lang: SepaLang, scheme: SepaScheme): string[] => {
  const t = sepaTexts(lang)
  const de = lang !== 'en'
  return [
    de ? 'Ich bin zur Erteilung dieses Mandats für das angegebene Konto berechtigt (Kontoinhaber bzw. vertretungsberechtigt).' : 'I am entitled to grant this mandate for the account stated (account holder or authorised representative).',
    de ? 'Ich habe das SEPA-Lastschriftmandat gelesen und erteile es mit meiner elektronischen Unterschrift.' : 'I have read the SEPA direct debit mandate and grant it with my electronic signature.',
    scheme === 'B2B' ? t.noticeB2B : t.noticeCore,
    de ? 'Mir ist bekannt, dass ich das Mandat jederzeit schriftlich widerrufen kann.' : 'I am aware that I may revoke this mandate in writing at any time.'
  ]
}

/** Mandate reference: unique per mandate, ≤ 35 chars, A-Z 0-9 and - / only. */
export const buildMandateReference = (source: 'lead' | 'partner', recordId: number, seq: number | string): string => {
  const prefix = source === 'partner' ? 'BP' : 'LD'
  const stamp = new Date().toISOString().slice(0, 10).replace(/-/g, '')
  return `LY-${prefix}${recordId}-${stamp}-${String(seq).toUpperCase()}`.replace(/[^A-Z0-9\-/]/g, '').slice(0, 35)
}
