import { randomUUID } from 'crypto';
import { createStaticRacingSeed } from '@core/testing-support';
import type { IdentityProviderPort } from '../../application/ports/IdentityProviderPort';
import type { StartAuthCommandDTO } from '../../application/dto/StartAuthCommandDTO';
import type { AuthCallbackCommandDTO } from '../../application/dto/AuthCallbackCommandDTO';
import type { AuthenticatedUserDTO } from '../../application/dto/AuthenticatedUserDTO';

export class IracingDemoIdentityProviderAdapter implements IdentityProviderPort {
  private readonly seedDriverId: string;

  constructor() {
    const seed = createStaticRacingSeed(42);
    this.seedDriverId = seed.drivers[0]?.id ?? 'driver-1';
  }

  async startAuth(command: StartAuthCommandDTO): Promise<{ redirectUrl: string; state: string }> {
    const state = randomUUID();

    const params = new URLSearchParams();
    params.set('code', 'dummy-code');
    params.set('state', state);
    if (command.returnTo) {
      params.set('returnTo', command.returnTo);
    }

    return {
      redirectUrl: `/auth/iracing/callback?${params.toString()}`,
      state,
    };
  }

  async completeAuth(command: AuthCallbackCommandDTO): Promise<AuthenticatedUserDTO> {
    if (!command.code) {
      throw new Error('Missing auth code');
    }
    if (!command.state) {
      throw new Error('Missing auth state');
    }

    const user: AuthenticatedUserDTO = {
      id: 'demo-user',
      displayName: 'GridPilot Demo Driver',
      iracingCustomerId: '000000',
      primaryDriverId: this.seedDriverId,
      avatarUrl: `/api/avatar/${this.seedDriverId}`,
    };

    return user;
  }
}