import { describe, it, expect, afterEach } from 'vitest';
import path from 'node:path';
import { resolveDatabasePath } from '@/lib/db-file';

// resolveDatabasePath MUST agree with how Prisma resolves DATABASE_URL, or
// export-db/import-db operate on a different file than the live DB — the dev
// "0-byte export" bug (EVALUATION.md P1). Prisma resolves a relative `file:`
// URL against the schema dir (prisma/), not the cwd.

const original = process.env.DATABASE_URL;
afterEach(() => {
  if (original === undefined) delete process.env.DATABASE_URL;
  else process.env.DATABASE_URL = original;
});

describe('resolveDatabasePath', () => {
  it('resolves a relative file: URL against prisma/, matching Prisma', () => {
    process.env.DATABASE_URL = 'file:./data/app.db';
    expect(resolveDatabasePath()).toBe(
      path.resolve(process.cwd(), 'prisma', 'data', 'app.db'),
    );
  });

  it('strips a leading ./ but keeps the prisma/ anchor', () => {
    process.env.DATABASE_URL = 'file:data/app.db';
    expect(resolveDatabasePath()).toBe(
      path.resolve(process.cwd(), 'prisma', 'data', 'app.db'),
    );
  });

  it('returns an absolute file: path unchanged (production /data)', () => {
    process.env.DATABASE_URL = 'file:/data/app.db';
    expect(resolveDatabasePath()).toBe('/data/app.db');
  });
});
