import bcrypt from 'bcryptjs';
import { Like } from 'typeorm';
import { AppDataSource, User } from '../models/index.js';
import { AppError } from '../middleware/error.js';
import { ERROR_CODES, HTTP_STATUS } from '@media-manager/shared';
import type { CreateUserRequest, UpdateUserRequest, User as UserType, PaginatedData } from '@media-manager/shared';

interface GetUsersParams {
  page: number;
  pageSize: number;
  keyword?: string;
  role?: string;
  status?: string;
}

export class UserService {
  private userRepository = AppDataSource.getRepository(User);

  /**
   * 获取用户列表
   */
  async getUsers(params: GetUsersParams): Promise<PaginatedData<UserType>> {
    const { page, pageSize, keyword, role, status } = params;
    const skip = (page - 1) * pageSize;

    const queryBuilder = this.userRepository.createQueryBuilder('user');

    if (keyword) {
      queryBuilder.andWhere(
        '(user.username LIKE :keyword OR user.email LIKE :keyword OR user.nickname LIKE :keyword)',
        { keyword: `%${keyword}%` }
      );
    }

    if (role) {
      queryBuilder.andWhere('user.role = :role', { role });
    }

    if (status) {
      queryBuilder.andWhere('user.status = :status', { status });
    }

    const [users, total] = await queryBuilder
      .orderBy('user.createdAt', 'DESC')
      .skip(skip)
      .take(pageSize)
      .getManyAndCount();

    return {
      items: users.map(this.formatUser),
      total,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize),
    };
  }

  /**
   * 根据 ID 获取用户
   */
  async getUserById(id: number): Promise<UserType> {
    const user = await this.userRepository.findOne({
      where: { id },
    });

    if (!user) {
      throw new AppError('用户不存在', HTTP_STATUS.NOT_FOUND, ERROR_CODES.USER_NOT_FOUND);
    }

    return this.formatUser(user);
  }

  /**
   * 创建用户
   */
  async createUser(data: CreateUserRequest): Promise<UserType> {
    // 检查用户名是否已存在
    const existingUser = await this.userRepository.findOne({
      where: [{ username: data.username }, { email: data.email }],
    });

    if (existingUser) {
      throw new AppError('用户名或邮箱已存在', HTTP_STATUS.CONFLICT, ERROR_CODES.USER_EXISTS);
    }

    // 创建用户
    const passwordHash = await bcrypt.hash(data.password, 10);
    const user = this.userRepository.create({
      username: data.username,
      email: data.email || null,
      passwordHash,
      nickname: data.nickname || data.username,
      role: data.role || 'operator',
      status: 'active',
    });

    await this.userRepository.save(user);

    return this.formatUser(user);
  }

  /**
   * 更新用户
   */
  async updateUser(id: number, data: UpdateUserRequest): Promise<UserType> {
    const user = await this.userRepository.findOne({
      where: { id },
    });

    if (!user) {
      throw new AppError('用户不存在', HTTP_STATUS.NOT_FOUND, ERROR_CODES.USER_NOT_FOUND);
    }

    // 如果更新邮箱，检查是否已存在
    if (data.email && data.email !== user.email) {
      const existingUser = await this.userRepository.findOne({
        where: { email: data.email },
      });
      if (existingUser) {
        throw new AppError('邮箱已被使用', HTTP_STATUS.CONFLICT, ERROR_CODES.USER_EXISTS);
      }
    }

    // 如果更新密码
    let passwordHash = user.passwordHash;
    if (data.password) {
      passwordHash = await bcrypt.hash(data.password, 10);
    }

    // 更新用户
    await this.userRepository.update(id, {
      username: data.username ?? user.username,
      email: data.email ?? user.email,
      nickname: data.nickname ?? user.nickname,
      role: data.role ?? user.role,
      status: data.status ?? user.status,
      passwordHash,
    });

    const updatedUser = await this.userRepository.findOne({
      where: { id },
    });

    return this.formatUser(updatedUser!);
  }

  /**
   * 删除用户
   */
  async deleteUser(id: number, currentUserId: number): Promise<void> {
    if (id === currentUserId) {
      throw new AppError('不能删除自己', HTTP_STATUS.BAD_REQUEST, ERROR_CODES.VALIDATION);
    }

    const user = await this.userRepository.findOne({
      where: { id },
    });

    if (!user) {
      throw new AppError('用户不存在', HTTP_STATUS.NOT_FOUND, ERROR_CODES.USER_NOT_FOUND);
    }

    await this.userRepository.delete(id);
  }

  /**
   * 格式化用户数据
   */
  private formatUser(user: User): UserType {
    return {
      id: user.id,
      username: user.username,
      email: user.email,
      nickname: user.nickname,
      avatarUrl: user.avatarUrl,
      role: user.role,
      status: user.status,
      lastLoginAt: user.lastLoginAt?.toISOString() || null,
      lastLoginIp: user.lastLoginIp,
      createdAt: user.createdAt.toISOString(),
      updatedAt: user.updatedAt.toISOString(),
    };
  }
}
