'use server';

import { getSupabaseServerAdminClient } from '@kit/supabase/server-admin-client';

export interface AccountBenefitStatistics {
  benefitDistributionSchedule: {
    amount: number;
  };
  companyAccountsCount: number;
  periodTotal: number;
  orders: {
    totalSum: number;

    analysesCount: number;
    analysesSum: number;

    analysisPackagesCount: number;
    analysisPackagesSum: number;
  };
}

export const loadCompanyPersonalAccountsBalanceEntries = async ({
  accountId,
}: {
  accountId: string;
}) => {
  const supabase = getSupabaseServerAdminClient();

  const { count, data: accountMemberships } = await supabase
    .schema('medreport')
    .from('accounts_memberships')
    .select('user_id', { count: 'exact' })
    .eq('account_id', accountId)
    .throwOnError();

  const { data: accountBalanceEntries } = await supabase
    .schema('medreport')
    .from('account_balance_entries')
    .select('*')
    .eq('is_active', true)
    .in(
      'account_id',
      accountMemberships.map(({ user_id }) => user_id),
    )
    .throwOnError();

  const purchaseEntries = accountBalanceEntries.filter(
    ({ entry_type }) => entry_type === 'purchase',
  );
  const analysesEntries = purchaseEntries.filter(
    ({ is_analysis_order }) => is_analysis_order,
  );
  const analysisPackagesEntries = purchaseEntries.filter(
    ({ is_analysis_package_order }) => is_analysis_package_order,
  );

  return {
    accountBalanceEntries,
    analysesEntries,
    analysisPackagesEntries,
    companyAccountsCount: count || 0,
    purchaseEntries,
    purchaseEntriesTotal: purchaseEntries.reduce(
      (acc, { amount }) => acc + Math.abs(amount || 0),
      0,
    ),
  };
};

export const loadAccountBenefitStatistics = async (
  accountId: string,
): Promise<AccountBenefitStatistics> => {
  const supabase = getSupabaseServerAdminClient();

  const {
    analysesEntries,
    analysisPackagesEntries,
    companyAccountsCount,
    purchaseEntriesTotal,
  } = await loadCompanyPersonalAccountsBalanceEntries({ accountId });

  const { data: benefitDistributionSchedule } = await supabase
    .schema('medreport')
    .from('benefit_distribution_schedule')
    .select('*')
    .eq('company_id', accountId)
    .eq('is_active', true)
    .single();

  const scheduleAmount = benefitDistributionSchedule?.benefit_amount || 0;
  return {
    companyAccountsCount,
    benefitDistributionSchedule: {
      amount: benefitDistributionSchedule?.benefit_amount || 0,
    },
    periodTotal: scheduleAmount * companyAccountsCount,
    orders: {
      totalSum: purchaseEntriesTotal,

      analysesCount: analysesEntries.length,
      analysesSum: analysesEntries.reduce(
        (acc, { amount }) => acc + Math.abs(amount || 0),
        0,
      ),

      analysisPackagesCount: analysisPackagesEntries.length,
      analysisPackagesSum: analysisPackagesEntries.reduce(
        (acc, { amount }) => acc + Math.abs(amount || 0),
        0,
      ),
    },
  };
};
