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

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

import { AccountSubmitData } from './actions/update-account-actions';

/**
 * Class representing an API for interacting with user accounts.
 * @constructor
 * @param {SupabaseClient<Database>} client - The Supabase client instance.
 */
class AuthApi {
  constructor(private readonly client: SupabaseClient<Database>) {}

  /**
   * @name hasPersonalCode
   * @description Check if given account ID has added personal code.
   * @param id
   */
  async hasPersonalCode(id: string) {
    const { data, error } = await this.client.rpc('has_personal_code', {
      account_id: id,
    });

    if (error) {
      throw error;
    }

    return data;
  }

  /**
   * @name updateAccount
   * @description Update required fields for the account.
   * @param data
   */
  async updateAccount(data: AccountSubmitData) {
    const {
      data: { user },
    } = await this.client.auth.getUser();

    if (!user) {
      throw new Error('User not authenticated');
    }

    const { error } = await this.client.rpc('update_account', {
      p_name: data.firstName,
      p_last_name: data.lastName,
      p_personal_code: data.personalCode,
      p_phone: data.phone || '',
      p_city: data.city || '',
      p_has_consent_personal_data: data.userConsent,
      p_uid: user.id,
    });

    if (error) {
      throw error;
    }

    if (data.height || data.weight) {
      await this.updateAccountParams(data);
    }
  }

  /**
   * @name updateAccountParams
   * @description Update account parameters.
   * @param data
   */
  async updateAccountParams(data: AccountSubmitData) {
    const {
      data: { user },
    } = await this.client.auth.getUser();

    if (!user) {
      throw new Error('User not authenticated');
    }
    console.log('test', user, data);
    const response = await this.client.from('account_params').insert({
      account_id: user.id,
      height: data.height,
      weight: data.weight,
    });

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

export function createAuthApi(client: SupabaseClient<Database>) {
  return new AuthApi(client);
}
