import { jwtVerify } from 'jose';
import { describe, expect, it } from 'vitest';
import { HostClaimsSchema, JWT_AUDIENCE, JWT_ISSUER, TvClaimsSchema } from '@pintrush/protocol';
import { joinUrl, signHostToken, signTvToken, tvUrl } from './tokens';

const key = new TextEncoder().encode(process.env.AUTH_SECRET || 'dev-only-insecure-secret-change-me-0123456789');
const room = { id: '0b3f3c2a-6d55-4f0e-9a43-2b8d7d7c9c11', venueId: '7e0f2d55-1c4b-4c0e-8a39-5f2a8f3d1e22', tvTokenVersion: 3 };

describe('web socket tokens', () => {
  it('mints TV tokens the game server accepts (display scope, versioned, no expiry)', async () => {
    const { payload } = await jwtVerify(await signTvToken({ roomId: room.id, venueId: room.venueId, v: 3 }), key, { issuer: JWT_ISSUER, audience: JWT_AUDIENCE });
    expect(TvClaimsSchema.parse(payload)).toEqual({ scope: 'tv', roomId: room.id, venueId: room.venueId, v: 3 });
    expect(payload.exp).toBeUndefined();
  });

  it('mints 12-hour host tokens scoped to one venue', async () => {
    const { payload } = await jwtVerify(await signHostToken({ sub: '5a1d2c3b-0000-4000-8000-000000000001', venueId: room.venueId, role: 'OWNER' }), key, { issuer: JWT_ISSUER, audience: JWT_AUDIENCE });
    expect(HostClaimsSchema.parse(payload).venueId).toBe(room.venueId);
    expect((payload.exp ?? 0) - (payload.iat ?? 0)).toBe(12 * 3600);
  });

  it('builds TV and join URLs', async () => {
    expect(await tvUrl('https://pintrush.com/', room)).toMatch(/^https:\/\/pintrush\.com\/tv\/0b3f3c2a-6d55-4f0e-9a43-2b8d7d7c9c11\?t=ey/);
    expect(joinUrl('https://pintrush.com', 'HARBOR', room.id)).toBe(`https://pintrush.com/join/HARBOR?room=${room.id}`);
  });
});
