/**
 * controller.ts (addresses)
 *
 *   GET  /api/addresses/colonias  → catálogo público de colonias
 *   GET  /api/addresses/me        → dirección activa del usuario logueado
 *   PUT  /api/addresses/me        → asignar colonia al usuario logueado
 */

import { Request, Response } from "express";
import { AuthRequest } from "../middlewares/auth.middleware.js";
import { CustomError } from "../../domain/errors/custom.error.js";
import { ListColoniasUseCase } from "../../domain/use-cases/addresses/list-colonias.use-case.js";
import { GetMyAddressUseCase } from "../../domain/use-cases/addresses/get-my-address.use-case.js";
import { SetMyAddressUseCase } from "../../domain/use-cases/addresses/set-my-address.use-case.js";

export class AddressesController {
  private listColonias = new ListColoniasUseCase();
  private getMyAddress = new GetMyAddressUseCase();
  private setMyAddress = new SetMyAddressUseCase();

  colonias = (_req: Request, res: Response) => {
    try {
      const result = this.listColonias.execute();
      res.status(200).json(result);
    } catch (error) {
      this.handleError(error, res);
    }
  };

  myAddress = (req: AuthRequest, res: Response) => {
    try {
      if (!req.user) throw CustomError.unauthorized("User not authenticated");
      const result = this.getMyAddress.execute(req.user.id);
      res.status(200).json(result);
    } catch (error) {
      this.handleError(error, res);
    }
  };

  setAddress = (req: AuthRequest, res: Response) => {
    try {
      if (!req.user) throw CustomError.unauthorized("User not authenticated");
      const result = this.setMyAddress.execute(
        req.user.id,
        req.user.email, // como fallback de nombre
        req.user.email,
        req.body,
      );
      res.status(200).json(result);
    } catch (error) {
      this.handleError(error, res);
    }
  };

  private handleError(error: unknown, res: Response): void {
    if (error instanceof CustomError) {
      res.status(error.statusCode).json({ error: error.message });
      return;
    }
    if (error instanceof Error) {
      res.status(400).json({ error: error.message });
      return;
    }
    res.status(500).json({ error: "Internal server error" });
  }
}
