import { Request, Response } from 'express';
import * as contractCategoryService from '../services/contractCategory.service.js';
import { logChange } from '../services/audit.service.js';
import { ApiResponse } from '../types/index.js';
import { pickContractCategoryUpdate } from '../utils/sanitize.js';

export async function getContractCategories(req: Request, res: Response): Promise<void> {
  try {
    const includeInactive = req.query.includeInactive === 'true';
    const categories = await contractCategoryService.getAllContractCategories(includeInactive);
    res.json({ success: true, data: categories } as ApiResponse);
  } catch (error) {
    res.status(500).json({
      success: false,
      error: 'Fehler beim Laden der Vertragskategorien',
    } as ApiResponse);
  }
}

export async function getContractCategory(req: Request, res: Response): Promise<void> {
  try {
    const category = await contractCategoryService.getContractCategoryById(parseInt(req.params.id));
    if (!category) {
      res.status(404).json({
        success: false,
        error: 'Vertragskategorie nicht gefunden',
      } as ApiResponse);
      return;
    }
    res.json({ success: true, data: category } as ApiResponse);
  } catch (error) {
    res.status(500).json({
      success: false,
      error: 'Fehler beim Laden der Vertragskategorie',
    } as ApiResponse);
  }
}

export async function createContractCategory(req: Request, res: Response): Promise<void> {
  try {
    const category = await contractCategoryService.createContractCategory(req.body);
    await logChange({
      req, action: 'CREATE', resourceType: 'ContractCategory',
      resourceId: category.id.toString(),
      label: `Vertragskategorie ${category.name} angelegt`,
    });
    res.status(201).json({ success: true, data: category } as ApiResponse);
  } catch (error) {
    res.status(400).json({
      success: false,
      error: error instanceof Error ? error.message : 'Fehler beim Erstellen der Vertragskategorie',
    } as ApiResponse);
  }
}

export async function updateContractCategory(req: Request, res: Response): Promise<void> {
  try {
    // Pentest R110: Mass-Assignment-Whitelist.
    const category = await contractCategoryService.updateContractCategory(parseInt(req.params.id), pickContractCategoryUpdate(req.body));
    await logChange({
      req, action: 'UPDATE', resourceType: 'ContractCategory',
      resourceId: category.id.toString(),
      label: `Vertragskategorie ${category.name} aktualisiert`,
    });
    res.json({ success: true, data: category } as ApiResponse);
  } catch (error) {
    res.status(400).json({
      success: false,
      error: error instanceof Error ? error.message : 'Fehler beim Aktualisieren der Vertragskategorie',
    } as ApiResponse);
  }
}

export async function deleteContractCategory(req: Request, res: Response): Promise<void> {
  try {
    const categoryId = parseInt(req.params.id);
    const category = await contractCategoryService.getContractCategoryById(categoryId);
    await contractCategoryService.deleteContractCategory(categoryId);
    await logChange({
      req, action: 'DELETE', resourceType: 'ContractCategory',
      resourceId: categoryId.toString(),
      label: `Vertragskategorie ${category?.name || categoryId} gelöscht`,
    });
    res.json({ success: true, message: 'Vertragskategorie gelöscht' } as ApiResponse);
  } catch (error) {
    res.status(400).json({
      success: false,
      error: error instanceof Error ? error.message : 'Fehler beim Löschen der Vertragskategorie',
    } as ApiResponse);
  }
}
