import { test, expect } from 'bun:test';
import { fixture } from '../habits/test-fixture';

test('export is complete, owned, and excludes sessions; deletion removes only the authenticated account', async () => {
  const f = fixture();
  try {
    const a = await f.json('/habits', 'POST', { name: 'Private tasks', method: 'tasks', tasks: [{ name: 'Stretch' }] }, 201);
    const b = await f.json('/habits', 'POST', { name: 'Bob only', method: 'manual' }, 201, 'b');
    const day = await f.json(`/habits/${a.id}/days/2026-09-04`);
    await f.json(`/habits/${a.id}/days/2026-09-04/tasks/${day.tasks[0].taskId}`, 'PUT', { done: true });
    await f.json('/charts', 'POST', { name: 'Mine', habitIds: [a.id] }, 201);
    const response = await f.request('/account/export');
    expect(response.headers.get('content-disposition')).toContain('attachment');
    const data = await response.json();
    expect(data.habits.map((h: any) => h.id)).toEqual([a.id]);
    expect(data.tasks[0].done).toBe(true);
    expect(data.progressEvents.length).toBe(1);
    expect(data.revisions.length).toBeGreaterThan(0);
    expect(data.charts.length).toBe(1);
    expect(JSON.stringify(data)).not.toContain('tokenHash');
    expect(JSON.stringify(data)).not.toContain('Bob only');
    expect((await f.request('/account', 'DELETE', { confirmation: 'DELETE' }, 'a', { Origin: 'https://wrong.test' })).status).toBe(403);
    expect((await f.request('/account', 'DELETE', {})).status).toBe(422);
    const removed = await f.request('/account', 'DELETE', { confirmation: 'DELETE' });
    expect(removed.status).toBe(204);
    expect(removed.headers.get('set-cookie')).toContain('Max-Age=0');
    expect((await f.request('/me')).status).toBe(401);
    expect((await f.request('/account/export')).status).toBe(401);
    expect((await f.json('/habits', 'GET', undefined, 200, 'b')).habits.map((h: any) => h.id)).toEqual([b.id]);
    expect(f.sqlite.query('PRAGMA foreign_key_check').all()).toEqual([]);
    expect(f.sqlite.query('SELECT * FROM progress_events').all()).toEqual([]);
  } finally { f.close(); }
});
