// src/controllers/user.ts
// Copyright (C) 2026 Robert Colbert <rob.colbert@openplatform.us>
// All Rights Reserved

import { NextFunction, Request, Response } from "express";

import UserService from "../services/user.js";
import { populateUserById } from "./lib/populators.js";

import { DtpController } from "../lib/controller.js";

export class UserController extends DtpController {
  get name(): string {
    return "UserController";
  }
  get slug(): string {
    return "user";
  }
  get route(): string {
    return "/user";
  }

  constructor() {
    super();
  }

  async start(): Promise<void> {
    const requireAdmin = this.requireAdmin();

    this.router.param("userId", populateUserById(this));

    this.router.post("/:userId", requireAdmin, this.postUserUpdate.bind(this));

    this.router.get("/:userId", requireAdmin, this.getUserView.bind(this));
    this.router.get("/", requireAdmin, this.getUserHome.bind(this));
  }

  async postUserUpdate(
    req: Request,
    res: Response,
    next: NextFunction
  ): Promise<void> {
    try {
      await UserService.updateForUser(res.locals.userAccount, req.body);
      res.status(200).json({
        success: true,
        user: res.locals.userAccount,
      });
    } catch (error) {
      this.log.error("failed to update user", { error });
      next(error);
    }
  }

  async getUserView(_req: Request, res: Response): Promise<void> {
    res.status(200).json({
      success: true,
      message: "User profile view",
    });
  }

  async getUserHome(
    req: Request,
    res: Response,
    next: NextFunction
  ): Promise<void> {
    try {
      const pagination = this.getPaginationParameters(req, 20);

      const query = req.query.q ? req.query.q.toString() : undefined;
      const recentUsers = await UserService.getRecent(pagination, query);

      res.status(200).json({
        success: true,
        users: recentUsers,
      });
    } catch (error) {
      this.log.error("failed to present User Admin home", { error });
      next(error);
    }
  }
}

export default UserController;
