import type {
  Article1Clause,
  ContractClausePack,
  ContractDirection,
  ContractFreight,
  ContractServiceScope,
} from './contract-template.types';

const STANDARD_CONTRACT_DOCUMENTS = [
  'Amendments (if any)',
  'This Contract Agreement',
  'Final Minutes of Negotiation (if any)',
];

const PAYMENT_OBLIGATION =
  'Pay 100% transportation fees in advance per train set in accordance with Article 5.';

const HAZARDOUS_OBLIGATION =
  'Notify EDR 48 hours in advance for hazardous or valuable cargo.';

function clonePack(pack: ContractClausePack): ContractClausePack {
  return {
    article1: {
      objective: pack.article1.objective,
      scope: [...pack.article1.scope],
    },
    clientObligations: [...pack.clientObligations],
    providerObligations: [...pack.providerObligations],
    contractDocuments: [...pack.contractDocuments],
  };
}

function applyForwardingOverlay(
  pack: ContractClausePack,
  service: ContractServiceScope,
): ContractClausePack {
  if (service !== 'FORWARDING') return pack;

  const next = clonePack(pack);
  next.article1.scope.push(
    'First-mile and/or last-mile coordination, documentation, and handover with road or port partners where included in the agreed service scope.',
  );
  next.providerObligations.push(
    'Coordinate first-mile and last-mile logistics with designated partners and keep the Client informed of handover milestones.',
  );
  return next;
}

function buildImportContainerPack(): ContractClausePack {
  return {
    article1: {
      objective:
        'To provide railway transportation for 40ft and/or 20ft full containers from SGTD to Dire Dawa, Modjo dry port and/or Galaan Multipurpose port (GMP), and empty container return from those terminals to SGTD.',
      scope: [
        'Railway transport service on the agreed import corridor.',
        'Cargo handling at Galaan Multipurpose port (GMP) where applicable.',
      ],
    },
    clientObligations: [
      'Provide shipment instructions to EDR for container movements on the agreed corridor.',
      'Meet minimum container supply per terminal (Modjo, Dire Dawa, GMP) as per EDR operational rules.',
      'Submit required documents to Djibouti Nagad station at least 24 hours before loading.',
      PAYMENT_OBLIGATION,
      HAZARDOUS_OBLIGATION,
    ],
    providerObligations: [
      'Assign voyage per operational schedule and notify train schedule 48 hours in advance.',
      'Provide safe transportation and deliver within agreed timelines when documents are complete.',
      'Return empty containers from Dire Dawa, Modjo and GMP to SGTD within seven (7) calendar days of receipt.',
      'Maintain cargo liability insurance per wagon.',
    ],
    contractDocuments: [...STANDARD_CONTRACT_DOCUMENTS],
  };
}

function buildImportBulkPack(): ContractClausePack {
  return {
    article1: {
      objective:
        'To provide railway transportation for bulk cargo from SGTD railway freight station at Djibouti to designated Ethiopian rail terminals on the import corridor.',
      scope: [
        'Railway bulk transport service on the agreed import corridor.',
        'Loading and unloading coordination at designated terminals per EDR operational rules.',
      ],
    },
    clientObligations: [
      'Provide accurate commodity description, weight, and shipment instructions for each train movement.',
      'Ensure cargo is prepared and available at origin per the agreed loading window.',
      'Submit required customs and operational documents at least 24 hours before loading where applicable.',
      PAYMENT_OBLIGATION,
      HAZARDOUS_OBLIGATION,
    ],
    providerObligations: [
      'Assign train capacity per operational schedule and notify departure timing 48 hours in advance where practicable.',
      'Provide safe bulk transportation and deliver within agreed timelines when documents are complete.',
      'Maintain cargo liability insurance per wagon or train consist as applicable.',
    ],
    contractDocuments: [...STANDARD_CONTRACT_DOCUMENTS],
  };
}

function buildExportContainerPack(): ContractClausePack {
  return {
    article1: {
      objective:
        'To provide railway transportation for 40ft and/or 20ft full containers from designated Ethiopian dry ports and terminals to SGTD and related export corridors.',
      scope: [
        'Railway export transport service on the agreed corridor.',
        'Terminal coordination at origin yards for export dispatch where applicable.',
      ],
    },
    clientObligations: [
      'Provide export shipment instructions and container release details for each movement.',
      'Ensure containers are available at origin terminals per EDR operational windows.',
      'Submit required export, customs, and operational documents at origin at least 24 hours before loading.',
      PAYMENT_OBLIGATION,
      HAZARDOUS_OBLIGATION,
    ],
    providerObligations: [
      'Assign voyage per operational schedule and notify train schedule 48 hours in advance.',
      'Provide safe transportation to SGTD and hand over for export processing when documents are complete.',
      'Maintain cargo liability insurance per wagon.',
    ],
    contractDocuments: [...STANDARD_CONTRACT_DOCUMENTS],
  };
}

function buildExportBulkPack(): ContractClausePack {
  return {
    article1: {
      objective:
        'To provide railway transportation for bulk export cargo from designated Ethiopian rail terminals to SGTD and related export corridors.',
      scope: [
        'Railway bulk export transport on the agreed corridor.',
        'Loading coordination at origin terminals per EDR operational rules.',
      ],
    },
    clientObligations: [
      'Provide accurate commodity description, weight, and export shipment instructions.',
      'Ensure bulk cargo is prepared and available at origin per the agreed loading window.',
      'Submit required export and customs documents at least 24 hours before loading where applicable.',
      PAYMENT_OBLIGATION,
      HAZARDOUS_OBLIGATION,
    ],
    providerObligations: [
      'Assign train capacity per operational schedule and notify departure timing 48 hours in advance where practicable.',
      'Provide safe bulk transportation to SGTD within agreed timelines when documents are complete.',
      'Maintain cargo liability insurance per wagon or train consist as applicable.',
    ],
    contractDocuments: [...STANDARD_CONTRACT_DOCUMENTS],
  };
}

function buildDomesticContainerPack(): ContractClausePack {
  return {
    article1: {
      objective:
        'To provide railway transportation for 40ft and/or 20ft containers between designated Ethiopian rail terminals on the domestic corridor.',
      scope: ['Domestic railway container transport between agreed origin and destination yards.'],
    },
    clientObligations: [
      'Provide shipment instructions for each domestic container movement.',
      'Ensure containers are available at origin per EDR operational rules.',
      PAYMENT_OBLIGATION,
      HAZARDOUS_OBLIGATION,
    ],
    providerObligations: [
      'Assign voyage per operational schedule and notify train schedule 48 hours in advance where practicable.',
      'Provide safe transportation and deliver within agreed timelines when instructions are complete.',
      'Maintain cargo liability insurance per wagon.',
    ],
    contractDocuments: [...STANDARD_CONTRACT_DOCUMENTS],
  };
}

function buildDomesticBulkPack(): ContractClausePack {
  return {
    article1: {
      objective:
        'To provide railway transportation for bulk cargo between designated Ethiopian rail terminals on the domestic corridor.',
      scope: ['Domestic railway bulk transport between agreed origin and destination terminals.'],
    },
    clientObligations: [
      'Provide commodity description, weight, and shipment instructions for each movement.',
      'Ensure cargo is prepared at origin per the agreed loading window.',
      PAYMENT_OBLIGATION,
      HAZARDOUS_OBLIGATION,
    ],
    providerObligations: [
      'Assign train capacity per operational schedule and notify departure timing 48 hours in advance where practicable.',
      'Provide safe bulk transportation within agreed timelines.',
      'Maintain cargo liability insurance per wagon or train consist as applicable.',
    ],
    contractDocuments: [...STANDARD_CONTRACT_DOCUMENTS],
  };
}

const BASE_PACKS: Record<ContractDirection, Record<ContractFreight, () => ContractClausePack>> = {
  IMP: {
    CON: buildImportContainerPack,
    BULK: buildImportBulkPack,
  },
  EXP: {
    CON: buildExportContainerPack,
    BULK: buildExportBulkPack,
  },
  DOM: {
    CON: buildDomesticContainerPack,
    BULK: buildDomesticBulkPack,
  },
};

export function buildClausePack(
  direction: ContractDirection,
  freight: ContractFreight,
  service: ContractServiceScope,
): ContractClausePack {
  const base = BASE_PACKS[direction][freight]();
  return applyForwardingOverlay(base, service);
}

export function article1ObjectiveFromClause(article1: Article1Clause): string {
  return article1.objective;
}
