import { randomUUID } from 'crypto';
import type {
  AuthCallbackCommand,
  AuthenticatedUser,
  IdentityProviderPort,
  StartAuthCommand,
} from '@core/identity/application/ports/IdentityProviderPort';

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

  constructor() {
    this.seedDriverId = 'driver-1';
  }

  async startAuth(command: StartAuthCommand): 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: AuthCallbackCommand): Promise<AuthenticatedUser> {
    if (!command.code) {
      throw new Error('Missing auth code');
    }
    if (!command.state) {
      throw new Error('Missing auth state');
    }

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

    return user;
  }
}