import { CreateUserDTO, LoginDTO, AuthResponse } from "@calchat/shared";
import { UserRepository } from "./interfaces";
import * as password from "../utils/password";

export class AuthService {
  constructor(private userRepo: UserRepository) {}

  async login(data: LoginDTO): Promise<AuthResponse> {
    // Try email first, then userName
    let user = await this.userRepo.findByEmail(data.identifier);
    if (!user) {
      user = await this.userRepo.findByUserName(data.identifier);
    }

    if (!user || !user.passwordHash) {
      throw new Error("Invalid credentials");
    }

    const isValid = await password.compare(data.password, user.passwordHash);
    if (!isValid) {
      throw new Error("Invalid credentials");
    }

    return { user, accessToken: "" };
  }

  async register(data: CreateUserDTO): Promise<AuthResponse> {
    const existingEmail = await this.userRepo.findByEmail(data.email);
    if (existingEmail) {
      throw new Error("Email already exists");
    }

    const existingUserName = await this.userRepo.findByUserName(data.userName);
    if (existingUserName) {
      throw new Error("Username already exists");
    }

    const passwordHash = await password.hash(data.password);
    const user = await this.userRepo.create({
      email: data.email,
      userName: data.userName,
      passwordHash,
    });

    return { user, accessToken: "" };
  }
}
