import { getSupabaseClient } from '@/lib/supabase';
import type { ProcurementAccount1688, ProcurementAccount1688CreatePayload, ProcurementAccount1688UpdatePayload } from '@/types';

const TABLE = 'procurement_accounts_1688';

export async function fetchAccounts(userId: string): Promise<ProcurementAccount1688[]> {
  const supabase = getSupabaseClient();
  const { data, error } = await supabase
    .from(TABLE)
    .select('*')
    .eq('user_id', userId)
    .order('created_at', { ascending: false });

  if (error) throw error;
  return data ?? [];
}

export async function createAccount(userId: string, payload: ProcurementAccount1688CreatePayload): Promise<ProcurementAccount1688> {
  const supabase = getSupabaseClient();
  const { data, error } = await supabase
    .from(TABLE)
    .insert({
      user_id: userId,
      account_name: payload.account_name,
      password: payload.password,
      remark: payload.remark ?? null,
    })
    .select()
    .single();

  if (error) throw error;
  return data;
}

export async function updateAccount(id: string, payload: ProcurementAccount1688UpdatePayload): Promise<ProcurementAccount1688> {
  const supabase = getSupabaseClient();
  const { data, error } = await supabase
    .from(TABLE)
    .update({
      ...payload,
      updated_at: new Date().toISOString(),
    })
    .eq('id', id)
    .select()
    .single();

  if (error) throw error;
  return data;
}

export async function deleteAccount(id: string): Promise<void> {
  const supabase = getSupabaseClient();
  const { error } = await supabase
    .from(TABLE)
    .delete()
    .eq('id', id);

  if (error) throw error;
}
