import { Response, NextFunction } from 'express';
import { AuthenticatedRequest, ApiResponse } from '../../shared/types/index.js';
import { auditService } from './services/audit.instance.js';

export const auditController = {
  /**
   * Get audit logs with filters
   */
  async getLogs(req: AuthenticatedRequest, res: Response, next: NextFunction) {
    try {
      const {
        userId,
        entityType,
        action,
        startDate,
        endDate,
        page = 1,
        limit = 20
      } = req.query;

      const filters = {
        userId: userId as string,
        entityType: entityType as string,
        action: action as string,
        startDate: startDate ? new Date(startDate as string) : undefined,
        endDate: endDate ? new Date(endDate as string) : undefined,
      };

      const result = await auditService.findAuditLogs(
        req.user!.tenantId,
        filters,
        { page: Number(page), limit: Number(limit) }
      );

      const response: ApiResponse = {
        success: true,
        data: result.data,
        meta: {
            total: result.total,
            page: Number(page),
            limit: Number(limit),
            totalPages: Math.ceil(result.total / Number(limit))
        }
      };
      res.json(response);
    } catch (error) {
      next(error);
    }
  },

  /**
   * Get logs for a specific entity
   */
  async getEntityLogs(req: AuthenticatedRequest, res: Response, next: NextFunction) {
    try {
        const { entityType, entityId } = req.params;
        const result = await auditService.findAuditLogsByEntity(
            req.user!.tenantId,
            entityType,
            entityId
        );

        const response: ApiResponse = {
            success: true,
            data: result
        };
        res.json(response);
    } catch (error) {
        next(error);
    }
  }
};
