import { DataSource } from 'typeorm';
import { beforeEach, afterEach } from 'vitest';
import { UserEntity } from '@/server/modules/users/user.entity';
import { Role } from '@/server/modules/users/role.entity';
import { ActivityEntity, ActivityType } from '@/server/modules/activities/activity.entity';
import { RouteEntity } from '@/server/modules/routes/route.entity';
import { VehicleType } from '@/server/modules/routes/route.schema';
import { AppDataSource } from '@/server/data-source';

/**
 * 集成测试数据库工具类 - 使用真实PostgreSQL数据库
 */
export class IntegrationTestDatabase {
  /**
   * 清理集成测试数据库
   */
  static async cleanup(): Promise<void> {
    if (AppDataSource.isInitialized) {
      await AppDataSource.destroy();
    }
  }

  /**
   * 获取当前数据源
   */
  static async getDataSource(): Promise<DataSource> {
    if(!AppDataSource.isInitialized) {
      await AppDataSource.initialize();
    }
    return AppDataSource
  }
}

/**
 * 测试数据工厂类
 */
export class TestDataFactory {
  /**
   * 创建测试用户数据
   */
  static createUserData(overrides: Partial<UserEntity> = {}): Partial<UserEntity> {
    const timestamp = Date.now();
    return {
      username: `testuser_${timestamp}`,
      password: 'TestPassword123!',
      email: `test_${timestamp}@example.com`,
      phone: `138${timestamp.toString().slice(-8)}`,
      nickname: `Test User ${timestamp}`,
      name: `Test Name ${timestamp}`,
      isDisabled: 0,
      isDeleted: 0,
      ...overrides
    };
  }

  /**
   * 创建测试角色数据
   */
  static createRoleData(overrides: Partial<Role> = {}): Partial<Role> {
    const timestamp = Date.now();
    return {
      name: `test_role_${timestamp}`,
      description: `Test role description ${timestamp}`,
      ...overrides
    };
  }

  /**
   * 在数据库中创建测试用户
   */
  static async createTestUser(dataSource: DataSource, overrides: Partial<UserEntity> = {}): Promise<UserEntity> {
    const userData = this.createUserData(overrides);
    const userRepository = dataSource.getRepository(UserEntity);

    const user = userRepository.create(userData);
    return await userRepository.save(user);
  }

  /**
   * 在数据库中创建测试角色
   */
  static async createTestRole(dataSource: DataSource, overrides: Partial<Role> = {}): Promise<Role> {
    const roleData = this.createRoleData(overrides);
    const roleRepository = dataSource.getRepository(Role);

    const role = roleRepository.create(roleData);
    return await roleRepository.save(role);
  }

  /**
   * 创建测试活动数据
   */
  static createActivityData(overrides: Partial<ActivityEntity> = {}): Partial<ActivityEntity> {
    const timestamp = Date.now();
    const now = new Date();
    const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000);

    return {
      name: `测试活动_${timestamp}`,
      description: `测试活动描述_${timestamp}`,
      type: ActivityType.DEPARTURE,
      startDate: now,
      endDate: tomorrow,
      isDisabled: 0,
      isDeleted: 0,
      ...overrides
    };
  }

  /**
   * 创建测试路线数据
   */
  static createRouteData(overrides: Partial<RouteEntity> = {}): Partial<RouteEntity> {
    const timestamp = Date.now();
    const now = new Date();
    const departureTime = new Date(now.getTime() + 2 * 60 * 60 * 1000); // 2小时后

    return {
      name: `测试路线_${timestamp}`,
      startLocationId: 1,
      endLocationId: 2,
      pickupPoint: `上车点_${timestamp}`,
      dropoffPoint: `下车点_${timestamp}`,
      departureTime: departureTime,
      vehicleType: VehicleType.BUS,
      price: 100,
      seatCount: 40,
      availableSeats: 40,
      isDisabled: 0,
      isDeleted: 0,
      ...overrides
    };
  }

  /**
   * 在数据库中创建测试活动
   */
  static async createTestActivity(dataSource: DataSource, overrides: Partial<ActivityEntity> = {}): Promise<ActivityEntity> {
    const activityData = this.createActivityData(overrides);
    const activityRepository = dataSource.getRepository(ActivityEntity);

    const activity = activityRepository.create(activityData);
    return await activityRepository.save(activity);
  }

  /**
   * 在数据库中创建测试路线
   */
  static async createTestRoute(dataSource: DataSource, overrides: Partial<RouteEntity> = {}): Promise<RouteEntity> {
    const routeData = this.createRouteData(overrides);
    const routeRepository = dataSource.getRepository(RouteEntity);

    // 如果没有提供activityId，自动创建一个测试活动
    if (!routeData.activityId) {
      const testActivity = await this.createTestActivity(dataSource);
      routeData.activityId = testActivity.id;
    }

    const route = routeRepository.create(routeData);
    return await routeRepository.save(route);
  }
}

/**
 * 集成测试数据库生命周期钩子
 */
export function setupIntegrationDatabaseHooks() {
  beforeEach(async () => {
    await IntegrationTestDatabase.getDataSource();
  });

  afterEach(async () => {
    await IntegrationTestDatabase.cleanup();
  });
}