import { prisma } from "@/config/database.js";
import { env } from "@/config/env.js";
import { ApiResponse, JWTPayload, LoginRequest, RegisterRequest } from "@/types/index.js";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";

export class AuthService {
  static async register(data: RegisterRequest): Promise<ApiResponse> {
    try {
      const existingUser = await prisma.user.findFirst({
        where: {
          OR: [{ email: data.email }, { username: data.username }],
        },
      });

      if (existingUser) {
        return {
          success: false,
          error: existingUser.email === data.email ? "Email already exists" : "Username already exists",
        };
      }
      const hashedPassword = await bcrypt.hash(data.password, 12);

      const user = await prisma.user.create({
        data: {
          username: data.username,
          email: data.email,
          password: hashedPassword,
        },
      });

      const token = this.generateToken({
        userId: user.id,
        username: user.username,
        email: user.email,
      });

      return {
        success: true,
        data: {
          token,
          user: {
            id: user.id,
            username: user.username,
            email: user.email,
          },
        },
      };
    } catch (error) {
      console.error("Registration error:", error);
      return {
        success: false,
        error: "Registration failed",
      };
    }
  }

  static async login(data: LoginRequest): Promise<ApiResponse> {
    try {
      const user = await prisma.user.findUnique({
        where: {
          email: data.email,
        },
      });

      if (!user || !(await bcrypt.compare(data.password, user.password))) {
        return {
          success: false,
          error: "Invalid email or password",
        };
      }

      const token = this.generateToken({
        userId: user.id,
        username: user.username,
        email: user.email,
      });

      return {
        success: true,
        data: {
          token,
          user: {
            id: user.id,
            username: user.username,
            email: user.email,
          },
        },
      };
    } catch (error) {
      console.error("Login error:", error);
      return {
        success: false,
        error: "Login failed",
      };
    }
  }

  private static generateToken(payload: JWTPayload): string {
    return jwt.sign(payload, env.JWT_SECRET, { expiresIn: "7d" });
  }
}
