import { prisma } from "@/config/database.js";
import { ApiResponse, UpdateUserRequest } from "@/types/index.js";
import bcrypt from "bcryptjs";

export class UserService {
  static async updateProfile(userId: string, data: UpdateUserRequest): Promise<ApiResponse> {
    try {
      if (data.username) {
        const existingUser = await prisma.user.findFirst({
          where: {
            username: data.username,
            id: { not: userId },
          },
        });

        if (existingUser) {
          return {
            success: false,
            error: "Username already taken",
          };
        }
      }

      if (data.email) {
        const existingUser = await prisma.user.findFirst({
          where: {
            email: data.email,
            id: { not: userId },
          },
        });

        if (existingUser) {
          return {
            success: false,
            error: "Email already taken",
          };
        }
      }

      const updateData: Partial<UpdateUserRequest> = {};
      if (data.username) updateData.username = data.username;
      if (data.email) updateData.email = data.email;
      if (data.avatar !== undefined) updateData.avatar = data.avatar;

      if (data.password) {
        updateData.password = await bcrypt.hash(data.password, 12);
      }

      const updatedUser = await prisma.user.update({
        where: { id: userId },
        data: updateData,
        select: {
          id: true,
          username: true,
          email: true,
          avatar: true,
        },
      });

      return {
        success: true,
        data: updatedUser,
      };
    } catch (error) {
      console.error("Update profile error:", error);
      return {
        success: false,
        error: "Failed to update profile",
      };
    }
  }
}
