import 'server-only';

import { SupabaseClient } from '@supabase/supabase-js';

import { getSupabaseServerAdminClient } from '@/packages/supabase/src/clients/server-admin-client';
import { Database } from '@/packages/supabase/src/database.types';

import { loadTeamWorkspace } from '~/home/[account]/_lib/server/team-account-workspace.loader';

/**
 * Load data for the members page
 * @param client
 * @param slug
 */
export async function loadMembersPageData(
  client: SupabaseClient<Database>,
  slug: string,
) {
  const workspace = await loadTeamWorkspace(slug);
  return Promise.all([
    loadAccountMembers(client, slug),
    loadInvitations(client, slug),
    canAddMember,
    workspace,
    loadAccountMembersBenefitsUsage(
      getSupabaseServerAdminClient(),
      workspace.account.id,
    ),
  ]);
}

/**
 * @name canAddMember
 * @description Check if the current user can add a member to the account
 *
 * This needs additional logic to determine if the user can add a member to the account
 * Please implement the logic and return a boolean value
 *
 * The same check needs to be added when creating an invitation
 *
 */
async function canAddMember() {
  return Promise.resolve(true);
}

/**
 * Load account members
 * @param client
 * @param account
 */
async function loadAccountMembers(
  client: SupabaseClient<Database>,
  account: string,
) {
  const { data, error } = await client
    .schema('medreport')
    .rpc('get_account_members', {
      account_slug: account,
    });

  if (error) {
    console.error(error);
    throw error;
  }

  const members = data ?? [];

  return members.sort((prev, next) => {
    if (prev.primary_owner_user_id === prev.user_id) {
      return -1;
    }

    if (prev.role_hierarchy_level < next.role_hierarchy_level) {
      return -1;
    }

    return 1;
  });
}

export async function loadAccountMembersBenefitsUsage(
  client: SupabaseClient<Database>,
  accountId: string,
): Promise<
  {
    personal_account_id: string;
    benefit_amount: number;
    benefit_unused_amount: number;
  }[]
> {
  const { data, error } = await client
    .schema('medreport')
    .rpc('get_benefits_usages_for_company_members', {
      p_account_id: accountId,
    });

  if (error) {
    console.error('Failed to load account members benefits usage', error);
    return [];
  }

  return (data ?? []) as unknown as {
    personal_account_id: string;
    benefit_amount: number;
    benefit_unused_amount: number;
  }[];
}

/**
 * Load account invitations
 * @param client
 * @param account
 */
async function loadInvitations(
  client: SupabaseClient<Database>,
  account: string,
) {
  const { data, error } = await client
    .schema('medreport')
    .rpc('get_account_invitations', {
      account_slug: account,
    });

  if (error) {
    console.error(error);
    throw error;
  }

  return data ?? [];
}
