import 'reflect-metadata';

import { MediaResolverAdapter } from '@adapters/media/MediaResolverAdapter';
import { MediaGenerationService } from '@core/media/domain/services/MediaGenerationService';
import { Reflector } from '@nestjs/core';
import { Test, TestingModule } from '@nestjs/testing';
import type { Response } from 'express';
import request from 'supertest';
import { vi } from 'vitest';
import { AuthenticationGuard } from '../auth/AuthenticationGuard';
import { AuthorizationGuard } from '../auth/AuthorizationGuard';
import type { AuthorizationService } from '../auth/AuthorizationService';
import { FeatureAvailabilityGuard } from '../policy/FeatureAvailabilityGuard';
import type { PolicyService, PolicySnapshot } from '../policy/PolicyService';
import { DeleteMediaOutputDTO } from './dtos/DeleteMediaOutputDTO';
import { GetAvatarOutputDTO } from './dtos/GetAvatarOutputDTO';
import { GetMediaOutputDTO } from './dtos/GetMediaOutputDTO';
import { RequestAvatarGenerationInputDTO } from './dtos/RequestAvatarGenerationInputDTO';
import { RequestAvatarGenerationOutputDTO } from './dtos/RequestAvatarGenerationOutputDTO';
import { UpdateAvatarInputDTO } from './dtos/UpdateAvatarInputDTO';
import { UpdateAvatarOutputDTO } from './dtos/UpdateAvatarOutputDTO';
import { UploadMediaInputDTO } from './dtos/UploadMediaInputDTO';
import { UploadMediaOutputDTO } from './dtos/UploadMediaOutputDTO';
import { MediaController } from './MediaController';
import { MediaService } from './MediaService';
import { LOGGER_TOKEN, MEDIA_STORAGE_PORT_TOKEN } from './MediaTokens';
import type { MulterFile } from './types/MulterFile';

describe('MediaController', () => {
  let controller: MediaController;
  let service: MediaService & {
    requestAvatarGeneration: ReturnType<typeof vi.fn>;
    uploadMedia: ReturnType<typeof vi.fn>;
    getMedia: ReturnType<typeof vi.fn>;
    deleteMedia: ReturnType<typeof vi.fn>;
    getAvatar: ReturnType<typeof vi.fn>;
    updateAvatar: ReturnType<typeof vi.fn>;
    getUploadedMedia: ReturnType<typeof vi.fn>;
    resolveMediaReference: ReturnType<typeof vi.fn>;
  };
  let generationService: MediaGenerationService & {
    generateDriverAvatar: ReturnType<typeof vi.fn>;
    generateTeamLogo: ReturnType<typeof vi.fn>;
    generateLeagueLogo: ReturnType<typeof vi.fn>;
    generateLeagueCover: ReturnType<typeof vi.fn>;
    generateDefaultPNG: ReturnType<typeof vi.fn>;
  };

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [MediaController],
      providers: [
        {
          provide: MediaService,
          useValue: {
            requestAvatarGeneration: vi.fn(),
            uploadMedia: vi.fn(),
            getMedia: vi.fn(),
            deleteMedia: vi.fn(),
            getAvatar: vi.fn(),
            updateAvatar: vi.fn(),
            getUploadedMedia: vi.fn(),
            resolveMediaReference: vi.fn(),
          },
        },
        {
          provide: MediaGenerationService,
          useValue: {
            generateDriverAvatar: vi.fn(),
            generateTeamLogo: vi.fn(),
            generateLeagueLogo: vi.fn(),
            generateLeagueCover: vi.fn(),
            generateDefaultPNG: vi.fn(),
          },
        },
        {
          provide: MediaResolverAdapter,
          useValue: {
            resolve: vi.fn(),
          },
        },
        {
          provide: LOGGER_TOKEN,
          useValue: {
            debug: vi.fn(),
            info: vi.fn(),
            warn: vi.fn(),
            error: vi.fn(),
          },
        },
        {
          provide: MEDIA_STORAGE_PORT_TOKEN,
          useValue: {
            uploadMedia: vi.fn(),
            deleteMedia: vi.fn(),
            getBytes: vi.fn(),
            getMetadata: vi.fn(),
          },
        },
      ],
    }).compile();

    controller = module.get<MediaController>(MediaController);
    service = module.get(MediaService) as never;
    generationService = module.get(MediaGenerationService) as never;
  });

  const createMockResponse = (): Response => {
    const res: Partial<Response> = {};
    res.status = vi.fn().mockReturnValue(res as Response);
    res.json = vi.fn().mockReturnValue(res as Response);
    res.setHeader = vi.fn().mockReturnValue(res as Response);
    res.send = vi.fn().mockReturnValue(res as Response);
    return res as Response;
  };

  describe('requestAvatarGeneration', () => {
    it('should request avatar generation and return 201 on success', async () => {
      const input: RequestAvatarGenerationInputDTO = {
        userId: 'user-123',
        facePhotoData: 'photo-data',
        suitColor: 'red',
      };
      const dto: RequestAvatarGenerationOutputDTO = {
        success: true,
        requestId: 'req-123',
        avatarUrls: ['https://example.com/avatar.png'],
      };
      service.requestAvatarGeneration.mockResolvedValue(dto);

      const res = createMockResponse();

      await controller.requestAvatarGeneration(input, res);

      expect(service.requestAvatarGeneration).toHaveBeenCalledWith(input);
      expect(res.status).toHaveBeenCalledWith(201);
      expect(res.json).toHaveBeenCalledWith(dto);
    });

    it('should return 400 on failure', async () => {
      const input: RequestAvatarGenerationInputDTO = {
        userId: 'user-123',
        facePhotoData: 'photo-data',
        suitColor: 'red',
      };
      const dto: RequestAvatarGenerationOutputDTO = {
        success: false,
        errorMessage: 'Error',
      };
      service.requestAvatarGeneration.mockResolvedValue(dto);

      const res = createMockResponse();

      await controller.requestAvatarGeneration(input, res);

      expect(service.requestAvatarGeneration).toHaveBeenCalledWith(input);
      expect(res.status).toHaveBeenCalledWith(400);
      expect(res.json).toHaveBeenCalledWith(dto);
    });
  });

  describe('uploadMedia', () => {
    it('should upload media and return 201 on success', async () => {
      const file: MulterFile = { filename: 'file.jpg' } as MulterFile;
      const input: UploadMediaInputDTO = { type: 'image' } as UploadMediaInputDTO;
      const dto: UploadMediaOutputDTO = {
        success: true,
        mediaId: 'media-123',
        url: 'https://example.com/file.jpg',
      };
      service.uploadMedia.mockResolvedValue(dto);

      const res = createMockResponse();

      await controller.uploadMedia(file, input, res);

      expect(service.uploadMedia).toHaveBeenCalledWith({ ...input, file });
      expect(res.status).toHaveBeenCalledWith(201);
      expect(res.json).toHaveBeenCalledWith(dto);
    });

    it('should return 400 when upload fails', async () => {
      const file: MulterFile = { filename: 'file.jpg' } as MulterFile;
      const input: UploadMediaInputDTO = { type: 'image' } as UploadMediaInputDTO;
      const dto: UploadMediaOutputDTO = {
        success: false,
        error: 'Upload failed',
      };
      service.uploadMedia.mockResolvedValue(dto);

      const res = createMockResponse();

      await controller.uploadMedia(file, input, res);

      expect(service.uploadMedia).toHaveBeenCalledWith({ ...input, file });
      expect(res.status).toHaveBeenCalledWith(400);
      expect(res.json).toHaveBeenCalledWith(dto);
    });
  });

  describe('getTeamLogo', () => {
    it('should return generated team logo SVG', async () => {
      const teamId = 'team-123';
      const svg = '<svg>logo</svg>';
      generationService.generateTeamLogo.mockReturnValue(svg);

      const res = createMockResponse();

      await controller.getTeamLogo(teamId, res);

      expect(generationService.generateTeamLogo).toHaveBeenCalledWith(teamId);
      expect(res.setHeader).toHaveBeenCalledWith('Content-Type', 'image/svg+xml; charset=utf-8');
      expect(res.status).toHaveBeenCalledWith(200);
      expect(res.send).toHaveBeenCalledWith(svg);
    });
  });

  describe('getLeagueLogo', () => {
    it('should return generated league logo SVG', async () => {
      const leagueId = 'league-123';
      const svg = '<svg>league-logo</svg>';
      generationService.generateLeagueLogo.mockReturnValue(svg);

      const res = createMockResponse();

      await controller.getLeagueLogo(leagueId, res);

      expect(generationService.generateLeagueLogo).toHaveBeenCalledWith(leagueId);
      expect(res.setHeader).toHaveBeenCalledWith('Content-Type', 'image/svg+xml; charset=utf-8');
      expect(res.status).toHaveBeenCalledWith(200);
      expect(res.send).toHaveBeenCalledWith(svg);
    });
  });

  describe('getLeagueCover', () => {
    it('should return generated league cover SVG', async () => {
      const leagueId = 'league-123';
      const svg = '<svg>league-cover</svg>';
      generationService.generateLeagueCover.mockReturnValue(svg);

      const res = createMockResponse();

      await controller.getLeagueCover(leagueId, res);

      expect(generationService.generateLeagueCover).toHaveBeenCalledWith(leagueId);
      expect(res.setHeader).toHaveBeenCalledWith('Content-Type', 'image/svg+xml; charset=utf-8');
      expect(res.status).toHaveBeenCalledWith(200);
      expect(res.send).toHaveBeenCalledWith(svg);
    });
  });

  describe('getDriverAvatar', () => {
    it('should return generated driver avatar SVG', async () => {
      const driverId = 'driver-123';
      const svg = '<svg>avatar</svg>';
      generationService.generateDriverAvatar.mockReturnValue(svg);

      const res = createMockResponse();

      await controller.getDriverAvatar(driverId, res);

      expect(generationService.generateDriverAvatar).toHaveBeenCalledWith(driverId);
      expect(res.setHeader).toHaveBeenCalledWith('Content-Type', 'image/svg+xml; charset=utf-8');
      expect(res.status).toHaveBeenCalledWith(200);
      expect(res.send).toHaveBeenCalledWith(svg);
    });
  });

  describe('getDefaultMedia', () => {
    it('should return PNG with correct cache headers', async () => {
      const variant = 'logo';
      const pngBuffer = Buffer.from([0x89, 0x50, 0x4E, 0x47]); // PNG header
      generationService.generateDefaultPNG.mockReturnValue(pngBuffer);

      const res = createMockResponse();

      await controller.getDefaultMedia(variant, res);

      expect(generationService.generateDefaultPNG).toHaveBeenCalledWith(variant);
      expect(res.setHeader).toHaveBeenCalledWith('Content-Type', 'image/png');
      expect(res.setHeader).toHaveBeenCalledWith('Cache-Control', 'public, max-age=31536000, immutable');
      expect(res.status).toHaveBeenCalledWith(200);
      expect(res.send).toHaveBeenCalledWith(pngBuffer);
    });

    it('should handle different variants', async () => {
      const variants = ['logo', 'other-variant', 'another-variant'];
      
      for (const variant of variants) {
        const pngBuffer = Buffer.from([0x89, 0x50, 0x4E, 0x47]);
        generationService.generateDefaultPNG.mockReturnValue(pngBuffer);

        const res = createMockResponse();
        await controller.getDefaultMedia(variant, res);

        expect(generationService.generateDefaultPNG).toHaveBeenCalledWith(variant);
        expect(res.setHeader).toHaveBeenCalledWith('Cache-Control', 'public, max-age=31536000, immutable');
      }
    });
  });

  describe('getGeneratedMedia', () => {
    it('should return team logo SVG with long cache', async () => {
      const type = 'team';
      const id = '123';
      const svg = '<svg>team-logo</svg>';
      generationService.generateTeamLogo.mockReturnValue(svg);

      const res = createMockResponse();

      await controller.getGeneratedMedia(type, id, res);

      expect(generationService.generateTeamLogo).toHaveBeenCalledWith(id);
      expect(res.setHeader).toHaveBeenCalledWith('Content-Type', 'image/svg+xml; charset=utf-8');
      expect(res.setHeader).toHaveBeenCalledWith('Cache-Control', 'public, max-age=31536000, immutable');
      expect(res.status).toHaveBeenCalledWith(200);
      expect(res.send).toHaveBeenCalledWith(svg);
    });

    it('should return league logo SVG with long cache', async () => {
      const type = 'league';
      const id = '456';
      const svg = '<svg>league-logo</svg>';
      generationService.generateLeagueLogo.mockReturnValue(svg);

      const res = createMockResponse();

      await controller.getGeneratedMedia(type, id, res);

      expect(generationService.generateLeagueLogo).toHaveBeenCalledWith(id);
      expect(res.setHeader).toHaveBeenCalledWith('Content-Type', 'image/svg+xml; charset=utf-8');
      expect(res.setHeader).toHaveBeenCalledWith('Cache-Control', 'public, max-age=31536000, immutable');
      expect(res.status).toHaveBeenCalledWith(200);
      expect(res.send).toHaveBeenCalledWith(svg);
    });

    it('should return driver avatar SVG with long cache', async () => {
      const type = 'driver';
      const id = '789';
      const svg = '<svg>driver-avatar</svg>';
      generationService.generateDriverAvatar.mockReturnValue(svg);

      const res = createMockResponse();

      await controller.getGeneratedMedia(type, id, res);

      expect(generationService.generateDriverAvatar).toHaveBeenCalledWith(id);
      expect(res.setHeader).toHaveBeenCalledWith('Content-Type', 'image/svg+xml; charset=utf-8');
      expect(res.setHeader).toHaveBeenCalledWith('Cache-Control', 'public, max-age=31536000, immutable');
      expect(res.status).toHaveBeenCalledWith(200);
      expect(res.send).toHaveBeenCalledWith(svg);
    });

    it('should handle unknown types with fallback', async () => {
      const type = 'unknown';
      const id = '999';
      const svg = '<svg>fallback</svg>';
      generationService.generateLeagueLogo.mockReturnValue(svg);

      const res = createMockResponse();

      await controller.getGeneratedMedia(type, id, res);

      expect(generationService.generateLeagueLogo).toHaveBeenCalledWith('unknown-999');
      expect(res.setHeader).toHaveBeenCalledWith('Content-Type', 'image/svg+xml; charset=utf-8');
      expect(res.setHeader).toHaveBeenCalledWith('Cache-Control', 'public, max-age=31536000, immutable');
      expect(res.status).toHaveBeenCalledWith(200);
      expect(res.send).toHaveBeenCalledWith(svg);
    });
  });

  describe('getUploadedMedia', () => {
    it('should return uploaded media bytes with correct headers', async () => {
      const mediaId = 'media-123';
      const pngBuffer = Buffer.from([0x89, 0x50, 0x4E, 0x47]); // PNG header
      const mockStorage = {
        getBytes: vi.fn().mockResolvedValue(pngBuffer),
        getMetadata: vi.fn().mockResolvedValue({ size: 4, contentType: 'image/png' }),
      };
      const mockService = {
        getMedia: vi.fn().mockResolvedValue({ id: mediaId }),
        getUploadedMedia: vi.fn().mockResolvedValue({ bytes: pngBuffer, contentType: 'image/png' }),
      };

      const module = await Test.createTestingModule({
        controllers: [MediaController],
        providers: [
          {
            provide: MediaService,
            useValue: mockService,
          },
          {
            provide: MediaGenerationService,
            useValue: {},
          },
          {
            provide: MediaResolverAdapter,
            useValue: {},
          },
          {
            provide: LOGGER_TOKEN,
            useValue: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },
          },
          {
            provide: MEDIA_STORAGE_PORT_TOKEN,
            useValue: mockStorage,
          },
        ],
      }).compile();

      const testController = module.get<MediaController>(MediaController);
      const res = createMockResponse();

      await testController.getUploadedMedia(mediaId, res);

      expect(mockService.getMedia).toHaveBeenCalledWith(mediaId);
      expect(mockService.getUploadedMedia).toHaveBeenCalledWith('uploaded/media-123');
      expect(res.setHeader).toHaveBeenCalledWith('Content-Type', 'image/png');
      expect(res.setHeader).toHaveBeenCalledWith('Cache-Control', 'public, max-age=31536000, immutable');
      expect(res.status).toHaveBeenCalledWith(200);
      expect(res.send).toHaveBeenCalledWith(pngBuffer);
    });

    it('should return 404 when media not found', async () => {
      const mediaId = 'media-123';
      const mockStorage = {
        getBytes: vi.fn(),
        getMetadata: vi.fn(),
      };
      const mockService = {
        getMedia: vi.fn().mockResolvedValue(null),
      };

      const module = await Test.createTestingModule({
        controllers: [MediaController],
        providers: [
          {
            provide: MediaService,
            useValue: mockService,
          },
          {
            provide: MediaGenerationService,
            useValue: {},
          },
          {
            provide: MediaResolverAdapter,
            useValue: {},
          },
          {
            provide: LOGGER_TOKEN,
            useValue: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },
          },
          {
            provide: MEDIA_STORAGE_PORT_TOKEN,
            useValue: mockStorage,
          },
        ],
      }).compile();

      const testController = module.get<MediaController>(MediaController);
      const res = createMockResponse();

      await testController.getUploadedMedia(mediaId, res);

      expect(mockService.getMedia).toHaveBeenCalledWith(mediaId);
      expect(res.status).toHaveBeenCalledWith(404);
      expect(res.json).toHaveBeenCalledWith({ error: 'Media not found' });
    });
  });

  describe('getMedia', () => {
    it('should return media if found', async () => {
      const mediaId = 'media-123';
      const dto: GetMediaOutputDTO = {
        id: mediaId,
        url: 'https://example.com/file.jpg',
        type: 'image',
        category: 'avatar',
        uploadedAt: new Date(),
        size: 123,
      };
      service.getMedia.mockResolvedValue(dto);

      const res = createMockResponse();

      await controller.getMedia(mediaId, res);

      expect(service.getMedia).toHaveBeenCalledWith(mediaId);
      expect(res.status).toHaveBeenCalledWith(200);
      expect(res.json).toHaveBeenCalledWith(dto);
    });

    it('should return 404 if not found', async () => {
      const mediaId = 'media-123';
      service.getMedia.mockResolvedValue(null);

      const res = createMockResponse();

      await controller.getMedia(mediaId, res);

      expect(service.getMedia).toHaveBeenCalledWith(mediaId);
      expect(res.status).toHaveBeenCalledWith(404);
      expect(res.json).toHaveBeenCalledWith({ error: 'Media not found' });
    });
  });

  describe('deleteMedia', () => {
    it('should delete media and return result', async () => {
      const mediaId = 'media-123';
      const dto: DeleteMediaOutputDTO = {
        success: true,
      };
      service.deleteMedia.mockResolvedValue(dto);

      const res = createMockResponse();

      await controller.deleteMedia(mediaId, res);

      expect(service.deleteMedia).toHaveBeenCalledWith(mediaId);
      expect(res.status).toHaveBeenCalledWith(200);
      expect(res.json).toHaveBeenCalledWith(dto);
    });
  });

  describe('getAvatarDetails', () => {
    it('should return avatar if found', async () => {
      const driverId = 'driver-123';
      const dto: GetAvatarOutputDTO = {
        avatarUrl: 'https://example.com/avatar.png',
      };
      service.getAvatar.mockResolvedValue(dto);

      const res = createMockResponse();

      await controller.getAvatarDetails(driverId, res);

      expect(service.getAvatar).toHaveBeenCalledWith(driverId);
      expect(res.status).toHaveBeenCalledWith(200);
      expect(res.json).toHaveBeenCalledWith(dto);
    });

    it('should return 404 when avatar not found', async () => {
      const driverId = 'driver-123';
      service.getAvatar.mockResolvedValue(null);

      const res = createMockResponse();

      await controller.getAvatarDetails(driverId, res);

      expect(service.getAvatar).toHaveBeenCalledWith(driverId);
      expect(res.status).toHaveBeenCalledWith(404);
      expect(res.json).toHaveBeenCalledWith({ error: 'Avatar not found' });
    });
  });

  describe('updateAvatar', () => {
    it('should update avatar and return result', async () => {
      const driverId = 'driver-123';
      const input: UpdateAvatarInputDTO = { driverId: 'driver-123', avatarUrl: 'https://example.com/new-avatar.png' };
      const dto: UpdateAvatarOutputDTO = {
        success: true,
      };
      service.updateAvatar.mockResolvedValue(dto);

      const res = createMockResponse();

      await controller.updateAvatar(driverId, input, res);

      expect(service.updateAvatar).toHaveBeenCalledWith(driverId, input);
      expect(res.status).toHaveBeenCalledWith(200);
      expect(res.json).toHaveBeenCalledWith(dto);
    });
  });

  describe('auth guards (HTTP)', () => {
    let app: import("@nestjs/common").INestApplication;

    const sessionPort: { getCurrentSession: () => Promise<null | { token: string; user: { id: string } }> } = {
      getCurrentSession: vi.fn(async () => null),
    };

    const authorizationService: Pick<AuthorizationService, 'getRolesForUser'> = {
      getRolesForUser: vi.fn(() => []),
    };

    const policyService: Pick<PolicyService, 'getSnapshot'> = {
      getSnapshot: vi.fn(async (): Promise<PolicySnapshot> => ({
        policyVersion: 1,
        operationalMode: 'normal',
        maintenanceAllowlist: { view: [], mutate: [] },
        capabilities: {},
        loadedFrom: 'defaults',
        loadedAtIso: new Date(0).toISOString(),
      })),
    };

    beforeEach(async () => {
      const module = await Test.createTestingModule({
        controllers: [MediaController],
        providers: [
          {
            provide: MediaService,
            useValue: {
              getMedia: vi.fn(async () => ({ id: 'm1' })),
              deleteMedia: vi.fn(async () => ({ success: true })),
              requestAvatarGeneration: vi.fn(),
              uploadMedia: vi.fn(),
              getAvatar: vi.fn(),
              updateAvatar: vi.fn(),
              getUploadedMedia: vi.fn(async () => ({ bytes: Buffer.from([]), contentType: 'image/png' })),
              resolveMediaReference: vi.fn(async () => '/path'),
            },
          },
          {
            provide: MediaGenerationService,
            useValue: {
              generateDriverAvatar: vi.fn(() => '<svg>avatar</svg>'),
              generateTeamLogo: vi.fn(() => '<svg>logo</svg>'),
              generateLeagueLogo: vi.fn(() => '<svg>league</svg>'),
              generateDefaultPNG: vi.fn(() => Buffer.from([0x89, 0x50, 0x4E, 0x47])),
              generateLeagueCover: vi.fn(() => '<svg>cover</svg>'),
            },
          },
          {
            provide: MediaResolverAdapter,
            useValue: {
              resolve: vi.fn((ref) => {
                if (ref.type === 'system-default') {
                  return `/media/default/${ref.variant}`;
                }
                if (ref.type === 'generated') {
                  return `/media/generated/${ref.generationRequestId}`;
                }
                if (ref.type === 'uploaded') {
                  return `/media/uploaded/${ref.mediaId}`;
                }
                return null;
              }),
            },
          },
          {
            provide: LOGGER_TOKEN,
            useValue: {
              debug: vi.fn(),
              info: vi.fn(),
              warn: vi.fn(),
              error: vi.fn(),
            },
          },
          {
            provide: MEDIA_STORAGE_PORT_TOKEN,
            useValue: {
              uploadMedia: vi.fn(),
              deleteMedia: vi.fn(),
              getBytes: vi.fn(),
              getMetadata: vi.fn(),
            },
          },
        ],
      }).compile();

      app = module.createNestApplication();

      const reflector = new Reflector();
      app.useGlobalGuards(
        new AuthenticationGuard(sessionPort as never),
        new AuthorizationGuard(reflector, authorizationService as never),
        new FeatureAvailabilityGuard(reflector, policyService as never),
      );

      await app.init();
    });

    afterEach(async () => {
      await app?.close();
      vi.clearAllMocks();
    });

    it('allows @Public() endpoint without a session', async () => {
      await request(app.getHttpServer()).get('/media/m1').expect(200);
    });

    it('denies non-public endpoint by default when not authenticated (401)', async () => {
      await request(app.getHttpServer()).delete('/media/m1').expect(401);
    });

    it('allows non-public endpoint when authenticated via session port', async () => {
      vi.mocked(sessionPort.getCurrentSession).mockResolvedValueOnce({
        token: 't',
        user: { id: 'user-1' },
      });

      await request(app.getHttpServer()).delete('/media/m1').expect(200);
    });

    it('allows new public routes without authentication', async () => {
      // Test default media route
      await request(app.getHttpServer()).get('/media/default/male-default-avatar').expect(200);
      
      // Test generated media route
      await request(app.getHttpServer()).get('/media/generated/team/123').expect(200);
      
      // Test debug resolve route
      await request(app.getHttpServer()).get('/media/debug/resolve?type=system-default&variant=avatar').expect(200);
    });
  });
});
