import { Database } from 'bun:sqlite';
import { drizzle } from 'drizzle-orm/bun-sqlite';
import { migrate } from 'drizzle-orm/bun-sqlite/migrator';
import { createApi } from '../api';
import { hashToken } from '../auth';
import * as schema from '../db/schema';
export function fixture(path = ':memory:') {
  const sqlite = new Database(path); sqlite.exec('PRAGMA foreign_keys = ON');
  const db = drizzle(sqlite, { schema }); migrate(db, { migrationsFolder: './drizzle' });
  let time = Date.parse('2026-09-04T12:00:00Z');
  const origin = 'http://127.0.0.1:3000';
  const app = createApi(db, { origin, clientId: '', clientSecret: '', cookieSecret: 'test-only-secret-at-least-32-characters' }, undefined, () => time);
  for (const [id, token] of [['alice', 'a'], ['bob', 'b']]) {
    db.insert(schema.users).values({ id: id!, discordId: id!, username: id!, timezone: 'Europe/Belgrade', createdAt: time, updatedAt: time }).onConflictDoNothing().run();
    db.insert(schema.sessions).values({ tokenHash: hashToken(token!.repeat(43)), userId: id!, createdAt: time, expiresAt: time + 10 * 365 * 86400000 }).onConflictDoNothing().run();
  }
  async function request(path: string, method = 'GET', body?: unknown, user = 'a', extra?: Record<string, string>) {
    return app.request(`${origin}/api${path}`, { method, headers: { Cookie: `minabot_session=${user.repeat(43)}`, Origin: origin, 'Content-Type': 'application/json', ...extra }, body: body === undefined ? undefined : JSON.stringify(body) });
  }
  async function json(path: string, method = 'GET', body?: unknown, status = 200, user = 'a'): Promise<any> {
    const response = await request(path, method, body, user); const data = await response.json();
    if (response.status !== status) throw new Error(`${method} ${path}: expected ${status}, got ${response.status}: ${JSON.stringify(data)}`);
    return data;
  }
  return { sqlite, db, app, origin, request, json, setTime: (date: string) => { time = Date.parse(date); }, close: () => sqlite.close() };
}
