import 'server-only';

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

import type { ApplicationRole } from '@kit/accounts/types/accounts';
import { Database } from '@kit/supabase/database';

export function createAdminAccountsService(client: SupabaseClient<Database>) {
  return new AdminAccountsService(client);
}

class AdminAccountsService {
  constructor(private adminClient: SupabaseClient<Database>) {}

  async deleteAccount(accountId: string) {
    const { error } = await this.adminClient
      .schema('medreport')
      .from('accounts')
      .delete()
      .eq('id', accountId);

    if (error) {
      throw error;
    }
  }

  async updateRole(accountId: string, role: ApplicationRole) {
    const { error } = await this.adminClient
      .schema('medreport')
      .from('accounts')
      .update({ application_role: role })
      .eq('id', accountId);

    if (error) {
      throw error;
    }
  }

  async getAccount(accountId: string) {
    const { data } = await this.adminClient
      .schema('medreport')
      .from('accounts')
      .select('*')
      .eq('id', accountId)
      .single()
      .throwOnError();

    return data;
  }
}
