import { Request, Response } from 'express';
import { z } from 'zod';

import { NotFoundError } from '../../../errors/http-error';
import { getErrorMessage } from '../../../utils/error-utils';
import { UpdateUserProfileDto } from '../identity.dto';

import { profileService } from './profile.service';

/**
 * EN: Profile Management Controller
 * VI: Controller quản lý profile
 */
export class ProfileController {
  /**
   * EN: Get profile
   * VI: Lấy profile
   */
  async get(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const profile = await profileService.getProfile(id);

      if (!profile) {
        res.status(404).json({
          success: false,
          error: {
            code: 'PROFILE_NOT_FOUND',
            message: 'Profile not found / Profile không tìm thấy',
          },
        });
        return;
      }

      res.json({
        success: true,
        data: profile,
      });
    } catch (error: unknown) {
      res.status(500).json({
        success: false,
        error: {
          code: 'GET_PROFILE_FAILED',
          message: getErrorMessage(error) || 'Failed to get profile',
        },
      });
    }
  }

  /**
   * EN: Update profile
   * VI: Cập nhật profile
   */
  async update(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const data = UpdateUserProfileDto.parse(req.body);
      const profile = await profileService.updateProfile(id, data, req);

      res.json({
        success: true,
        data: profile,
        message: 'Profile updated successfully / Profile đã được cập nhật thành công',
      });
    } catch (error: unknown) {
      if (error instanceof z.ZodError) {
        res.status(400).json({
          success: false,
          error: {
            code: 'VALIDATION_ERROR',
            message: 'Invalid input',
            details: error.issues,
          },
        });
        return;
      }

      if (error instanceof NotFoundError) {
        res.status(404).json(error.toApiResponse());
        return;
      }

      res.status(500).json({
        success: false,
        error: {
          code: 'UPDATE_PROFILE_FAILED',
          message: getErrorMessage(error) || 'Failed to update profile',
        },
      });
    }
  }

  /**
   * EN: Upload avatar
   * VI: Upload avatar
   */
  async uploadAvatar(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const { avatarUrl } = req.body;

      if (!avatarUrl || typeof avatarUrl !== 'string') {
        res.status(400).json({
          success: false,
          error: {
            code: 'VALIDATION_ERROR',
            message: 'avatarUrl is required / avatarUrl là bắt buộc',
          },
        });
        return;
      }

      const profile = await profileService.uploadAvatar(id, avatarUrl, req);

      res.json({
        success: true,
        data: profile,
        message: 'Avatar uploaded successfully / Avatar đã được upload thành công',
      });
    } catch (error: unknown) {
      if (error instanceof NotFoundError) {
        res.status(404).json(error.toApiResponse());
        return;
      }

      res.status(500).json({
        success: false,
        error: {
          code: 'UPLOAD_AVATAR_FAILED',
          message: getErrorMessage(error) || 'Failed to upload avatar',
        },
      });
    }
  }

  /**
   * EN: Delete avatar
   * VI: Xóa avatar
   */
  async deleteAvatar(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const profile = await profileService.deleteAvatar(id, req);

      res.json({
        success: true,
        data: profile,
        message: 'Avatar deleted successfully / Avatar đã được xóa thành công',
      });
    } catch (error: unknown) {
      if (error instanceof NotFoundError) {
        res.status(404).json(error.toApiResponse());
        return;
      }

      res.status(500).json({
        success: false,
        error: {
          code: 'DELETE_AVATAR_FAILED',
          message: getErrorMessage(error) || 'Failed to delete avatar',
        },
      });
    }
  }
}

export const profileController = new ProfileController();
