import { Request, Response } from "express";
import { AuthenticatedRequest } from "../../middleware/auth";
import { authService } from "./auth.service";
import { handleError } from "../../utils/http";

export class AuthController {
  async register(_req: Request, res: Response) {
    // Maintain existing behavior: registration disabled
    return res.status(403).json({
      error: "Registration is disabled",
      message:
        "Only admins or managers can invite new users. Please use your invitation link to set your password.",
    });
  }

  async login(req: Request, res: Response) {
    try {
      const { email, password } = req.body || {};
      const result = await authService.login(email, password);
      return res.json(result);
    } catch (e: any) {
      const code = typeof e.code === "number" ? e.code : 500;
      const msg = code >= 500 ? "Login failed" : e.message || "Login failed";
      return handleError(res, msg, e, code);
    }
  }

  async me(req: AuthenticatedRequest, res: Response) {
    try {
      const userId = req.user!.userId;
      const user = await authService.getCurrentUser(userId);
      return res.json(user);
    } catch (e: any) {
      const code = typeof e.code === "number" ? e.code : 500;
      return handleError(res, e.message || "Failed to fetch current user", e, code);
    }
  }

  async forgotPassword(req: Request, res: Response) {
    const { email } = req.body || {};
    if (!email) {
      return res.status(400).json({ error: "Email is required" });
    }

    // Always respond with success, action is best-effort inside
    await authService.forgotPassword(email).catch(() => {});
    return res.json({
      message: "If an account exists for this email, a reset link was sent.",
    });
  }

  async resetPassword(req: Request, res: Response) {
    const { token, password } = req.body || {};
    if (!token || !password) {
      return res.status(400).json({ error: "Missing token or password" });
    }

    try {
      await authService.resetPassword(token, password);
      return res.json({ message: "Password has been reset" });
    } catch (e: any) {
      const code = typeof e.code === "number" ? e.code : 400;
      return handleError(res, e.message || "Invalid or expired token", e, code);
    }
  }
}

export const authController = new AuthController();
