import { logger } from '@goodgo/logger';
import { PrismaClient } from '@prisma/client';
import { Request } from 'express';

import { getPrismaClient } from '../../../config/database.config';
import { auditService } from '../../../core/events/audit.service';
import { NotFoundError } from '../../../errors/http-error';
import { UserProfileRepository } from '../../../repositories/user-profile.repository';
import { UpdateUserProfileDto } from '../identity.dto';

/**
 * EN: Profile Management Service
 * VI: Service quản lý profile
 */
export class ProfileService {
  private prisma: PrismaClient;
  private profileRepo: UserProfileRepository;

  constructor() {
    this.prisma = getPrismaClient();
    this.profileRepo = new UserProfileRepository(this.prisma);
  }

  /**
   * EN: Get user profile
   * VI: Lấy profile của user
   */
  async getProfile(userId: string): Promise<any> {
    const profile = await this.profileRepo.findByUserId(userId);
    if (!profile) {
      // Return empty profile if not exists
      return null;
    }
    return profile;
  }

  /**
   * EN: Update user profile
   * VI: Cập nhật profile của user
   */
  async updateProfile(userId: string, data: UpdateUserProfileDto, req?: Request): Promise<any> {
    // Verify user exists
    const user = await this.prisma.user.findUnique({ where: { id: userId } });
    if (!user) {
      throw new NotFoundError('User');
    }

    const profile = await this.profileRepo.upsert(userId, data);

    if (req) {
      await auditService.logFromRequest(req, 'PROFILE_UPDATED', {
        userId,
        success: true,
      });
    }

    logger.info('Profile updated', { userId });

    return profile;
  }

  /**
   * EN: Upload avatar (placeholder - actual file upload would need file storage service)
   * VI: Upload avatar (placeholder - upload file thực tế cần file storage service)
   */
  async uploadAvatar(userId: string, avatarUrl: string, req?: Request): Promise<any> {
    // Verify user exists
    const user = await this.prisma.user.findUnique({ where: { id: userId } });
    if (!user) {
      throw new NotFoundError('User');
    }

    const profile = await this.profileRepo.updateAvatar(userId, avatarUrl);

    if (req) {
      await auditService.logFromRequest(req, 'AVATAR_UPLOADED', {
        userId,
        success: true,
      });
    }

    logger.info('Avatar uploaded', { userId });

    return profile;
  }

  /**
   * EN: Delete avatar
   * VI: Xóa avatar
   */
  async deleteAvatar(userId: string, req?: Request): Promise<any> {
    // Verify user exists
    const user = await this.prisma.user.findUnique({ where: { id: userId } });
    if (!user) {
      throw new NotFoundError('User');
    }

    const profile = await this.profileRepo.removeAvatar(userId);

    if (req) {
      await auditService.logFromRequest(req, 'AVATAR_DELETED', {
        userId,
        success: true,
      });
    }

    logger.info('Avatar deleted', { userId });

    return profile;
  }

  /**
   * EN: Update user preferences
   * VI: Cập nhật preferences của user
   */
  async updatePreferences(userId: string, preferences: Record<string, any>, req?: Request): Promise<any> {
    // Verify user exists
    const user = await this.prisma.user.findUnique({ where: { id: userId } });
    if (!user) {
      throw new NotFoundError('User');
    }

    const profile = await this.profileRepo.upsert(userId, { preferences });

    if (req) {
      await auditService.logFromRequest(req, 'PREFERENCES_UPDATED', {
        userId,
        success: true,
      });
    }

    logger.info('Preferences updated', { userId });

    return profile;
  }
}

export const profileService = new ProfileService();
