import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';

import { loadCompanyPersonalAccountsBalanceEntries } from './load-team-account-benefit-statistics';

export interface TeamAccountBenefitExpensesOverview {
  benefitAmount: number | null;
  benefitOccurrence: 'yearly' | 'monthly' | 'quarterly' | null;
  currentMonthUsageTotal: number;
  managementFee: number;
  managementFeeTotal: number;
  total: number;
}

const MANAGEMENT_FEE = 5.5;

const MONTHS = 12;
const QUARTERS = 4;

export async function loadTeamAccountBenefitExpensesOverview({
  companyId,
  employeeCount,
}: {
  companyId: string;
  employeeCount: number;
}): Promise<TeamAccountBenefitExpensesOverview> {
  const supabase = getSupabaseServerClient();
  const { data, error } = await supabase
    .schema('medreport')
    .from('benefit_distribution_schedule')
    .select('*')
    .eq('company_id', companyId)
    .eq('is_active', true)
    .single();

  let benefitAmount: TeamAccountBenefitExpensesOverview['benefitAmount'] = null;
  let benefitOccurrence: TeamAccountBenefitExpensesOverview['benefitOccurrence'] =
    null;
  if (error) {
    console.warn('Failed to load team account benefit expenses overview');
  } else {
    benefitAmount =
      data.benefit_amount as TeamAccountBenefitExpensesOverview['benefitAmount'];
    benefitOccurrence =
      data.benefit_occurrence as TeamAccountBenefitExpensesOverview['benefitOccurrence'];
  }

  const { purchaseEntriesTotal } =
    await loadCompanyPersonalAccountsBalanceEntries({ accountId: companyId });

  return {
    benefitAmount,
    benefitOccurrence,
    currentMonthUsageTotal: purchaseEntriesTotal,
    managementFee: MANAGEMENT_FEE,
    managementFeeTotal: MANAGEMENT_FEE * employeeCount,
    total: (() => {
      if (typeof benefitAmount !== 'number') {
        return 0;
      }

      const currentDate = new Date();
      const createdAt = new Date(data.created_at);
      const isCreatedThisYear =
        createdAt.getFullYear() === currentDate.getFullYear();
      if (benefitOccurrence === 'yearly') {
        return benefitAmount * employeeCount;
      } else if (benefitOccurrence === 'monthly') {
        const monthsLeft = isCreatedThisYear
          ? MONTHS - createdAt.getMonth()
          : MONTHS;
        return benefitAmount * employeeCount * monthsLeft;
      } else if (benefitOccurrence === 'quarterly') {
        const quartersLeft = isCreatedThisYear
          ? QUARTERS - Math.ceil(createdAt.getMonth() / 3)
          : QUARTERS;
        return benefitAmount * employeeCount * quartersLeft;
      }
      return 0;
    })(),
  };
}
