import { PrismaClient } from '@prisma/client';

let prisma: PrismaClient | null = null;

export function getPrismaClient(): PrismaClient {
  if (!prisma) {
    prisma = new PrismaClient({
      datasources: {
        db: {
          url: process.env.DATABASE_URL,
        },
      },
    });
  }
  return prisma;
}

export async function cleanDatabase(): Promise<void> {
  const client = getPrismaClient();

  // Delete in correct order due to foreign key constraints
  await client.shareAccessLog.deleteMany();
  await client.backupShare.deleteMany();
}

export async function disconnectDatabase(): Promise<void> {
  if (prisma) {
    await prisma.$disconnect();
    prisma = null;
  }
}

export async function seedTestData(): Promise<void> {
  const client = getPrismaClient();

  // Seed some test data if needed
  await client.backupShare.create({
    data: {
      userId: BigInt(999999),
      accountSequence: BigInt(999999),
      publicKey: '02' + 'f'.repeat(64),
      partyIndex: 2,
      threshold: 2,
      totalParties: 3,
      encryptedShareData: 'seed-encrypted-data',
      encryptionKeyId: 'test-key-v1',
      status: 'ACTIVE',
    },
  });
}
