/**
 * Regression guard — a locked/released event rejects uploads with the DISTINCT error code
 * `uploads_locked` (not the generic `forbidden`), so the offline upload queue can tell this
 * REVERSIBLE 403 apart from a permanent one (banned / quota). On `uploads_locked` the client
 * KEEPS the queued blob and retries when the host reopens; a permanent 403 purges it. Before
 * this, a photo staged during a lock was purged and lost the moment the host reopened.
 */
import { test, expect } from '../../fixtures/test';
import { uploadRaw } from '../../helpers/upload-client';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { BASE } from '../../helpers/env';

const SAMPLE = () => readFileSync(join(process.cwd(), 'fixtures', 'media', 'sample.jpg'));

test.describe('Upload — locked event uses a distinct, reversible 403 (audit fix)', () => {
  test('closed event → 403 uploads_locked; reopen → upload succeeds', async ({ host, api }) => {
    // Close the event: uploads are locked for everyone.
    await api.closeEvent(host.jwt);

    const locked = await uploadRaw(host.jwt, SAMPLE(), {
      filename: 'during-lock.jpg',
      contentType: 'image/jpeg',
    });
    expect(locked.status).toBe(403);
    const lockedBody = await locked.json();
    // The distinct code is what tells the client to KEEP the blob (reversible), not purge it.
    expect(lockedBody.error).toBe('uploads_locked');

    // Reopen → the same upload now goes through (the queued blob would have survived).
    await api.openEvent(host.jwt);
    const ok = await uploadRaw(host.jwt, SAMPLE(), {
      filename: 'after-reopen.jpg',
      contentType: 'image/jpeg',
    });
    expect(ok.status, 'upload succeeds once the host reopens').toBeLessThan(300);
  });

  test('released gallery → 403 gallery_released, the PARKING code (not uploads_locked)', async ({
    host,
  }) => {
    // `release ⇒ lock`, so a released gallery satisfies both conditions and the handler's check
    // ORDER decides which code the guest gets. It must be the release one, and the difference is
    // not cosmetic: `uploads_locked` charges a retry attempt and re-pushes the whole photo on the
    // backoff ladder, against an answer that cannot change until a host acts. `gallery_released`
    // parks it — blob kept, nothing re-sent, and the guest is told to ask the hosts to reopen.
    // This asserted `uploads_locked` while the release branch was unreachable dead code.
    const rel = await fetch(`${BASE}/api/v1/host/gallery/release`, {
      method: 'POST',
      headers: { Authorization: `Bearer ${host.jwt}` },
    });
    expect(rel.status).toBe(204);

    const rejected = await uploadRaw(host.jwt, SAMPLE(), {
      filename: 'after-release.jpg',
      contentType: 'image/jpeg',
    });
    expect(rejected.status).toBe(403);
    const body = await rejected.json();
    expect(body.error).toBe('gallery_released');
  });
});
