import { Request, Response } from "express";
import { sendSuccess, sendPaginated } from "../../common/utils/api-response";
import * as clientService from "./client.service";

export async function inviteClient(req: Request, res: Response) {
  const organizationId = req.tenantId!;
  const result = await clientService.inviteClient(organizationId, req.body);
  sendSuccess(res, result, 201);
}

export async function acceptInvitation(req: Request, res: Response) {
  const { token, password } = req.body;
  const result = await clientService.acceptInvitation(token, password);
  sendSuccess(res, result, 201);
}

export async function getClients(req: Request, res: Response) {
  const organizationId = req.tenantId!;
  const page = Math.max(1, parseInt(String(req.query.page ?? "1")));
  const limit = Math.min(100, Math.max(1, parseInt(String(req.query.limit ?? "10"))));
  const search = req.query.search ? String(req.query.search) : undefined;
  const status = req.query.status ? String(req.query.status) : undefined;
  const { data, total } = await clientService.getClients(organizationId, page, limit, search, status);
  sendPaginated(res, data, total, page, limit);
}

export async function getClient(req: Request, res: Response) {
  const organizationId = req.tenantId!;
  const result = await clientService.getClient(req.params.id, organizationId);
  sendSuccess(res, result);
}

export async function updateClient(req: Request, res: Response) {
  const organizationId = req.tenantId!;
  const result = await clientService.updateClient(req.params.id, organizationId, req.body);
  sendSuccess(res, result);
}

export async function deleteClient(req: Request, res: Response) {
  const organizationId = req.tenantId!;
  await clientService.deleteClient(req.params.id, organizationId);
  sendSuccess(res, { message: "Client deleted successfully" });
}
