import { beforeEach, describe, expect, it, vi } from 'vitest';

import { getSupabaseClient } from '@/lib/supabase';
import { deleteAccount, isAccountDeleteRestrictedError } from '@/services/accountService';

vi.mock('@/lib/supabase', () => ({
  getSupabaseClient: vi.fn(),
}));

describe('account service', () => {
  beforeEach(() => {
    vi.resetAllMocks();
  });

  it('deletes a 1688 procurement account by id', async () => {
    const eq = vi.fn(async () => ({ error: null }));
    const deleteFn = vi.fn(() => ({ eq }));
    const from = vi.fn(() => ({ delete: deleteFn }));
    vi.mocked(getSupabaseClient).mockReturnValue({ from } as unknown as ReturnType<typeof getSupabaseClient>);

    await expect(deleteAccount('account-1')).resolves.toBeUndefined();

    expect(from).toHaveBeenCalledWith('procurement_accounts_1688');
    expect(deleteFn).toHaveBeenCalledTimes(1);
    expect(eq).toHaveBeenCalledWith('id', 'account-1');
  });

  it('recognizes Supabase foreign-key delete conflicts', () => {
    expect(isAccountDeleteRestrictedError({
      code: '23503',
      message: 'update or delete on table "procurement_accounts_1688" violates foreign key constraint',
    })).toBe(true);

    expect(isAccountDeleteRestrictedError({
      code: '409',
      message: 'Conflict',
    })).toBe(true);
  });
});
