import 'server-only';

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

import { getLogger } from '@kit/shared/logger';
import { Database } from '@kit/supabase/database';

export function createCreateCompanyAccountService(
  client: SupabaseClient<Database>,
) {
  return new CreateTeamAccountService(client);
}

class CreateTeamAccountService {
  private readonly namespace = 'accounts.create-team-account';

  constructor(private readonly client: SupabaseClient<Database>) {}

  async createNewOrganizationAccount(params: {
    name: string;
    ownerPersonalCode: string;
  }) {
    const logger = await getLogger();
    const ctx = { ...params, namespace: this.namespace };

    logger.info(ctx, `Creating new company account...`);

    const { error, data } = await this.client
      .schema('medreport')
      .rpc('create_team_account', {
        account_name: params.name,
        new_personal_code: params.ownerPersonalCode,
      });

    if (error) {
      logger.error(
        {
          error: error.message,
          ...ctx,
        },
        `Error creating company account`,
      );

      throw new Error('Error creating company account: ' + error);
    }

    logger.info(ctx, `Company account created successfully`);

    return { data, error };
  }
}
