
import { SignupWithEmailUseCase } from '@core/identity/application/use-cases/SignupWithEmailUseCase';
import { CreateAchievementUseCase } from '@core/identity/application/use-cases/achievement/CreateAchievementUseCase';
import type { Logger } from '@core/shared/domain/Logger';

import {
    ADMIN_ACHIEVEMENTS,
    COMMUNITY_ACHIEVEMENTS,
    DRIVER_ACHIEVEMENTS,
    STEWARD_ACHIEVEMENTS,
} from '@core/identity/domain/AchievementConstants';


export class EnsureInitialData {
  constructor(
    private readonly signupUseCase: SignupWithEmailUseCase,
    private readonly createAchievementUseCase: CreateAchievementUseCase,
    private readonly logger: Logger,
  ) {}

  async execute(): Promise<void> {
    // Ensure initial admin user exists
    const signupResult = await this.signupUseCase.execute({
      email: 'admin@gridpilot.local',
      password: 'admin123',
      displayName: 'Admin',
    });

    if (signupResult.isOk()) {
      this.logger.info('[Bootstrap] Initial admin user created');
    } else if (signupResult.error?.code === 'EMAIL_ALREADY_EXISTS') {
      this.logger.info('[Bootstrap] Admin user already exists');
    } else {
      const detailsMessage =
        signupResult.error && typeof signupResult.error === 'object' && 'details' in signupResult.error
          ? (signupResult.error as { details?: { message?: string } }).details?.message
          : undefined;

      throw new Error(detailsMessage ?? 'Failed to ensure initial admin user');
    }

    // Ensure initial achievements exist
    const allAchievements = [
      ...DRIVER_ACHIEVEMENTS,
      ...STEWARD_ACHIEVEMENTS,
      ...ADMIN_ACHIEVEMENTS,
      ...COMMUNITY_ACHIEVEMENTS,
    ];

    let createdCount = 0;
    let existingCount = 0;

    for (const achievementProps of allAchievements) {
      try {
        await this.createAchievementUseCase.execute(achievementProps);
        createdCount++;
      } catch {
        // If achievement already exists, that's fine
        existingCount++;
      }
    }

    this.logger.info(`[Bootstrap] Achievements: ${createdCount} created, ${existingCount} already exist`);

    // Create additional users for comprehensive seeding
    await this.createAdditionalUsers();

    // Create user achievements linking users to achievements
    await this.createUserAchievements();
  }

  private async createAdditionalUsers(): Promise<void> {
    const userConfigs = [
      // Driver with iRacing linked
      { displayName: 'Max Verstappen', email: 'max@racing.com', password: 'Test123!', iracingCustomerId: '12345' },
      // Driver without email
      { displayName: 'Lewis Hamilton', email: undefined, password: undefined, iracingCustomerId: '67890' },
      // Sponsor user
      { displayName: 'Sponsor Inc', email: 'sponsor@example.com', password: 'Test123!', iracingCustomerId: undefined },
      // Various driver profiles
      { displayName: 'Charles Leclerc', email: 'charles@ferrari.com', password: 'Test123!', iracingCustomerId: '11111' },
      { displayName: 'Lando Norris', email: 'lando@mclaren.com', password: 'Test123!', iracingCustomerId: '22222' },
      { displayName: 'George Russell', email: 'george@mercedes.com', password: 'Test123!', iracingCustomerId: '33333' },
      { displayName: 'Carlos Sainz', email: 'carlos@ferrari.com', password: 'Test123!', iracingCustomerId: '44444' },
      { displayName: 'Fernando Alonso', email: 'fernando@aston.com', password: 'Test123!', iracingCustomerId: '55555' },
      { displayName: 'Sergio Perez', email: 'sergio@redbull.com', password: 'Test123!', iracingCustomerId: '66666' },
      { displayName: 'Valtteri Bottas', email: 'valtteri@sauber.com', password: 'Test123!', iracingCustomerId: '77777' },
    ];

    let createdCount = 0;

    for (const config of userConfigs) {
      if (!config.email) {
        // Skip users without email for now (would need different creation method)
        continue;
      }

      try {
        const result = await this.signupUseCase.execute({
          email: config.email,
          password: config.password!,
          displayName: config.displayName,
        });

        if (result.isOk()) {
          createdCount++;
        }
      } catch (error) {
        // User might already exist, skip
      }
    }

    this.logger.info(`[Bootstrap] Created ${createdCount} additional users`);
  }

  private async createUserAchievements(): Promise<void> {
    // This would require access to user and achievement repositories
    // For now, we'll log that this would be done
    this.logger.info('[Bootstrap] User achievements would be created here (requires repository access)');
  }
}
