import { __ } from '@rutatiina/ui/lib/translations';
import type { AssessmentData, Result, Terms } from '@nugsoft/loans/lib/types';

export type ApplicationValues = {
  member: string;
  product: string;
  principal: string;
  date: string;
  first_due: string;
  count: string;
  frequency: string;
  rate: string;
  basis: string;
  method: string;
  purpose: string;
  income: string;
  expenses: string;
  debts: string;
  recommendation: string;
  notes: string;
};
export type Draft = {
  uuid: string;
  reference: string;
  data: ApplicationValues;
  step: number;
  version: number;
  updated_at: string;
  application_id: number | null;
};
export type ApplicationPreview = {
  terms: Terms;
  quote: Result;
  assessment_data: AssessmentData | null;
  preview_checksum: string;
};

export function blankApplication(date: string, member = ''): ApplicationValues {
  return {
    member,
    product: '',
    principal: '',
    date,
    first_due: '',
    count: '12',
    frequency: 'monthly',
    rate: '',
    basis: '',
    method: '',
    purpose: '',
    income: '',
    expenses: '',
    debts: '',
    recommendation: '',
    notes: '',
  };
}

export function applicationPayload(
  values: ApplicationValues,
  assessed: boolean,
) {
  return {
    member_id: values.member,
    product_id: values.product,
    terms: {
      principal: values.principal,
      date: values.date,
      count: /^\d+$/.test(values.count)
        ? parseInt(values.count, 10)
        : values.count,
      frequency: values.frequency,
      ...(values.first_due ? { first_due: values.first_due } : {}),
      ...(values.rate ? { rate: values.rate } : {}),
      ...(values.basis ? { basis: values.basis } : {}),
      ...(values.method ? { method: values.method } : {}),
    },
    ...(assessed
      ? {
          assessment: {
            purpose: values.purpose,
            income: values.income,
            expenses: values.expenses,
            debts: values.debts,
            recommendation: values.recommendation,
            notes: values.notes,
          },
        }
      : {}),
  };
}

/** Format decimal-string UGX without passing money through Number. */
export function ugx(value: string | null | undefined): string {
  if (value == null || value === '') return '—';
  const [whole, fraction] = value.split('.');
  return `UGX ${whole.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}${fraction && fraction !== '00' ? `.${fraction}` : ''}`;
}

export class ApplicationHttpError extends Error {
  constructor(
    message: string,
    public status: number,
    public fields: Record<string, string[]> = {},
  ) {
    super(message);
  }
}

export async function applicationJson<T>(
  url: string,
  method: 'GET' | 'POST' | 'PUT' = 'GET',
  body?: unknown,
): Promise<T> {
  const cookie = document.cookie
    .split('; ')
    .find((item) => item.startsWith('XSRF-TOKEN='));
  const response = await fetch(url, {
    method,
    credentials: 'same-origin',
    headers: {
      Accept: 'application/json',
      'X-Requested-With': 'XMLHttpRequest',
      ...(body ? { 'Content-Type': 'application/json' } : {}),
      ...(cookie
        ? { 'X-XSRF-TOKEN': decodeURIComponent(cookie.slice(11)) }
        : {}),
    },
    ...(method !== 'GET' && body ? { body: JSON.stringify(body) } : {}),
  }).catch(() => {
    throw new ApplicationHttpError(
      __(
        'Could not reach Mfuko. Check your connection and retry. Your changes are still on this screen.',
      ),
      0,
    );
  });
  if (response.status === 401 || response.status === 419 || response.redirected)
    throw new ApplicationHttpError(
      __('Your session has expired. Sign in again, then retry saving.'),
      response.status,
    );

  const result = (await response.json().catch(() => null)) as {
    message?: string;
    errors?: Record<string, string[]>;
  } | null;
  if (!response.ok)
    throw new ApplicationHttpError(
      Object.values(result?.errors ?? {})[0]?.[0] ??
        result?.message ??
        response.statusText,
      response.status,
      result?.errors,
    );
  if (result === null)
    throw new ApplicationHttpError(
      __('Mfuko could not complete the request. Please retry.'),
      response.status,
    );
  return result as T;
}
