import { z } from "zod";
import { User } from "../models/User.js";
import { signAccessToken, signRefreshToken } from "../utils/tokens.js";

const registerSchema = z.object({
  fullName: z.string().min(2),
  email: z.string().email(),
  phone: z.string().optional(),
  password: z.string().min(8)
});

export async function register(request, response) {
  const data = registerSchema.parse(request.body);
  const exists = await User.exists({ email: data.email });
  if (exists) return response.status(409).json({ message: "Email already registered" });
  const user = await User.create(data);
  response.status(201).json({
    user: { id: user._id, fullName: user.fullName, email: user.email, role: user.role },
    accessToken: signAccessToken(user),
    refreshToken: signRefreshToken(user)
  });
}

export async function login(request, response) {
  const { email, password } = request.body;
  const user = await User.findOne({ email }).select("+password");
  if (!user || !(await user.comparePassword(password))) return response.status(401).json({ message: "Invalid login credentials" });
  response.json({
    user: { id: user._id, fullName: user.fullName, email: user.email, role: user.role },
    accessToken: signAccessToken(user),
    refreshToken: signRefreshToken(user)
  });
}

export async function otpDisabled(_request, response) {
  response.status(410).json({ message: "OTP is disabled. OMOSALA PRINTS uses password login and WhatsApp notifications." });
}
