import { HttpException } from '@nestjs/common'; import { Types } from 'mongoose'; import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from '../auth/allow-public-access.decorator'; import { ROLES_KEY } from '../auth/roles.decorator'; import { CompetitionCommandService } from './competition-command.service'; import { CompetitionController } from './competition.controller'; import { CompetitionQueryService } from './competition-query.service'; describe('CompetitionController', () => { it('marks the read endpoints public and writes a revision ETag', async () => { const { controller, queryService } = createHarness(); const response = { setHeader: jest.fn() }; const result = await controller.getDetail( COMMUNITY_ID, MATCH_ID, response as never, ); for (const method of ['getDetail', 'getTeamView'] as const) { expect( Reflect.getMetadata( METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, CompetitionController.prototype[method], ), ).toBe(true); } expect(response.setHeader).toHaveBeenCalledWith('ETag', '"7"'); expect(result).toMatchObject({ revision: 7 }); expect(queryService.getCompetition).toHaveBeenCalledWith({ communityId: COMMUNITY_ID, matchId: MATCH_ID, }); }); it('reads a team view by explicit team id without an authenticated caller', async () => { const { controller, queryService } = createHarness(); queryService.getTeamView.mockResolvedValue({ revision: 7 }); const response = { setHeader: jest.fn() }; const result = await controller.getTeamView( undefined, COMMUNITY_ID, MATCH_ID, TEAM_A_ID.toHexString(), response as never, ); expect(queryService.getTeamView).toHaveBeenCalledWith({ communityId: COMMUNITY_ID, matchId: MATCH_ID, teamId: TEAM_A_ID, }); expect(response.setHeader).toHaveBeenCalledWith('ETag', '"7"'); expect(result).toMatchObject({ revision: 7 }); }); it('falls back to the membership-scoped team view for a signed-in caller', async () => { const { controller, queryService } = createHarness(); queryService.getTeamView.mockResolvedValue({ revision: 7 }); await controller.getTeamView(adminUser(), COMMUNITY_ID, MATCH_ID); expect(queryService.getTeamView).toHaveBeenCalledWith({ communityId: COMMUNITY_ID, matchId: MATCH_ID, userId: ADMIN_ID, }); }); it('rejects an anonymous team view request that names no team', async () => { const { controller, queryService } = createHarness(); await expect( controller.getTeamView(undefined, COMMUNITY_ID, MATCH_ID), ).rejects.toMatchObject({ status: 401, response: { error: { code: 'COMPETITION_TEAM_UNIDENTIFIED' } }, }); expect(queryService.getTeamView).not.toHaveBeenCalled(); }); it('rejects a malformed team id', async () => { const { controller, queryService } = createHarness(); await expect( controller.getTeamView(undefined, COMMUNITY_ID, MATCH_ID, 'not-an-id'), ).rejects.toMatchObject({ status: 422, response: { error: { code: 'INVALID_COMPETITION_REQUEST' } }, }); expect(queryService.getTeamView).not.toHaveBeenCalled(); }); it('protects audit and mutation endpoints with admin roles', () => { for (const method of [ 'listFacts', 'acceptGame', 'adjudicateSeries', 'previewReversal', 'reverseSeries', ] as const) { expect( Reflect.getMetadata(ROLES_KEY, CompetitionController.prototype[method]), ).toEqual(['owner', 'admin']); } }); it('requires If-Match and Idempotency-Key for a mutation', async () => { const { controller } = createHarness(); await expect( controller.acceptGame( adminUser(), COMMUNITY_ID, MATCH_ID, undefined, undefined, acceptGameBody(), ), ).rejects.toMatchObject({ status: 422, response: { error: { code: 'INVALID_COMPETITION_COMMAND_HEADERS' }, }, }); }); it('passes revision, idempotency and the authenticated actor to accept-game', async () => { const { controller, commandService } = createHarness(); await controller.acceptGame( adminUser(), COMMUNITY_ID, MATCH_ID, 'W/"7"', 'operator:accept:1', acceptGameBody(), ); expect(commandService.acceptGame).toHaveBeenCalledWith( expect.objectContaining({ expectedRevision: 7, idempotencyKey: 'operator:accept:1', }), ); const accepted = commandService.acceptGame.mock.calls[0][0]; expect(accepted.competitionId.toHexString()).toBe( COMPETITION_ID.toHexString(), ); expect(accepted.actor.userId.toHexString()).toBe(ADMIN_ID.toHexString()); expect(accepted.gameId.toHexString()).toBe(GAME_ID.toHexString()); expect(accepted.seriesId.toHexString()).toBe(SERIES_ID); expect(accepted.gameSlotId.toHexString()).toBe(GAME_SLOT_ID.toHexString()); }); it('maps command conflicts to the explicit error envelope', async () => { const { controller, commandService } = createHarness(); commandService.adjudicateSeries.mockRejectedValue({ code: 'IDEMPOTENCY_KEY_CONFLICT', message: 'duplicate key with another payload', httpStatus: 409, details: { idempotencyKey: 'same-key' }, }); let thrown: unknown; try { await controller.adjudicateSeries( adminUser(), COMMUNITY_ID, MATCH_ID, new Types.ObjectId(SERIES_ID), '"7"', 'same-key', { decision: { type: 'administrative-draw' }, reason: '운영 판단', }, ); } catch (error) { thrown = error; } expect(thrown).toBeInstanceOf(HttpException); expect(thrown).toMatchObject({ status: 409, response: { error: { code: 'IDEMPOTENCY_KEY_CONFLICT', details: { idempotencyKey: 'same-key' }, }, }, }); }); it.each([ { source: { code: 'STALE_COMPETITION_REVISION', message: 'stale', httpStatus: 412, }, status: 412, }, { source: { code: 'GAME_TEAM_MISMATCH', message: 'invalid evidence mapping', }, status: 422, }, ])('maps $source.code to HTTP $status', async ({ source, status }) => { const { controller, commandService } = createHarness(); commandService.acceptGame.mockRejectedValue(source); await expect( controller.acceptGame( adminUser(), COMMUNITY_ID, MATCH_ID, '"7"', `operator:error:${status}`, acceptGameBody(), ), ).rejects.toMatchObject({ status, response: { error: { code: source.code } }, }); }); it('returns an explicit 422 envelope for an invalid command body', async () => { const { controller, commandService } = createHarness(); await expect( controller.adjudicateSeries( adminUser(), COMMUNITY_ID, MATCH_ID, new Types.ObjectId(SERIES_ID), '"7"', 'operator:invalid-body:1', { decision: { type: 'walkover' }, reason: '', }, ), ).rejects.toMatchObject({ status: 422, response: { error: { code: 'INVALID_COMPETITION_REQUEST' }, }, }); expect(commandService.adjudicateSeries).not.toHaveBeenCalled(); }); it('rejects malformed game evidence before it reaches the ledger', async () => { const { controller, commandService } = createHarness(); await expect( controller.acceptGame( adminUser(), COMMUNITY_ID, MATCH_ID, '"7"', 'operator:bad-evidence:1', { ...acceptGameBody(), evidence: { type: 'invented-evidence' }, }, ), ).rejects.toMatchObject({ status: 422, response: { error: { code: 'INVALID_COMPETITION_REQUEST' }, }, }); expect(commandService.acceptGame).not.toHaveBeenCalled(); }); it('requires the same revision for preview and hash-confirmed reversal', async () => { const { controller, commandService } = createHarness(); await controller.previewReversal( adminUser(), COMMUNITY_ID, MATCH_ID, new Types.ObjectId(SERIES_ID), '"7"', { mode: 'cascade', reason: '잘못 수집됨' }, ); await controller.reverseSeries( adminUser(), COMMUNITY_ID, MATCH_ID, new Types.ObjectId(SERIES_ID), '"7"', 'operator:reverse:1', { mode: 'cascade', reason: '잘못 수집됨', impactHash: 'a'.repeat(64), }, ); expect(commandService.previewSeriesReversal).toHaveBeenCalledWith({ competitionId: COMPETITION_ID, expectedRevision: 7, seriesId: new Types.ObjectId(SERIES_ID), mode: 'cascade', }); expect(commandService.reverseSeries).toHaveBeenCalledWith( expect.objectContaining({ competitionId: COMPETITION_ID, expectedRevision: 7, idempotencyKey: 'operator:reverse:1', impactHash: 'a'.repeat(64), }), ); }); }); const COMMUNITY_ID = new Types.ObjectId('64d000000000000000000001'); const MATCH_ID = new Types.ObjectId('64d000000000000000000002'); const COMPETITION_ID = new Types.ObjectId('64d000000000000000000003'); const ADMIN_ID = new Types.ObjectId('64d000000000000000000004'); const GAME_ID = new Types.ObjectId('64d000000000000000000005'); const SERIES_ID = '64d000000000000000000006'; const GAME_SLOT_ID = new Types.ObjectId('64d000000000000000000007'); const TEAM_A_ID = new Types.ObjectId('64d000000000000000000008'); const TEAM_B_ID = new Types.ObjectId('64d000000000000000000009'); function createHarness() { const competition = { _id: COMPETITION_ID, matchId: MATCH_ID, communityId: COMMUNITY_ID, schemaVersion: 1, revision: 7, phase: 'running', teams: [], format: { type: 'paired-series', rule: { type: 'fixed-games', gameCount: 3, drawPolicy: 'allow' }, }, projection: { sourceRevision: 7, projectorVersion: 1, phase: 'running', formatType: 'paired-series', series: [], games: [], gameSlots: [], rounds: [], connectors: [], }, createdAt: new Date('2026-07-11T00:00:00.000Z'), updatedAt: new Date('2026-07-12T00:00:00.000Z'), }; const queryService = { getCompetition: jest.fn().mockResolvedValue(competition), getTeamView: jest.fn(), listFacts: jest.fn(), }; const commandService = { acceptGame: jest.fn().mockResolvedValue({ competition, revision: 8 }), adjudicateSeries: jest.fn().mockResolvedValue({ competition, revision: 8 }), previewSeriesReversal: jest.fn().mockResolvedValue({ sourceRevision: 7, impactHash: 'a'.repeat(64), impact: {}, }), reverseSeries: jest.fn().mockResolvedValue({ competition, revision: 8 }), }; return { queryService, commandService, controller: new CompetitionController( queryService as unknown as CompetitionQueryService, commandService as unknown as CompetitionCommandService, ), }; } function adminUser() { return { _id: ADMIN_ID, communityId: COMMUNITY_ID, role: 'admin', } as never; } function acceptGameBody() { return { gameId: GAME_ID.toHexString(), seriesId: SERIES_ID, gameSlotId: GAME_SLOT_ID.toHexString(), ordinal: 1, evidence: { type: 'riot', riotMatchId: 'KR_1', payloadHash: 'sha256:value', }, mapping: { mappingVersion: 1, confidence: 1, blueTeamId: TEAM_A_ID.toHexString(), redTeamId: TEAM_B_ID.toHexString(), winnerTeamId: TEAM_A_ID.toHexString(), }, }; }