import { Request, Response } from 'express';
import * as cancellationPeriodService from '../services/cancellation-period.service.js';
import { logChange } from '../services/audit.service.js';
import { ApiResponse } from '../types/index.js';
import { pickCancellationPeriodUpdate } from '../utils/sanitize.js';

export async function getCancellationPeriods(req: Request, res: Response): Promise<void> {
  try {
    const includeInactive = req.query.includeInactive === 'true';
    const periods = await cancellationPeriodService.getAllCancellationPeriods(includeInactive);
    res.json({ success: true, data: periods } as ApiResponse);
  } catch (error) {
    res.status(500).json({
      success: false,
      error: 'Fehler beim Laden der Kündigungsfristen',
    } as ApiResponse);
  }
}

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

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

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

export async function deleteCancellationPeriod(req: Request, res: Response): Promise<void> {
  try {
    const periodId = parseInt(req.params.id);
    const period = await cancellationPeriodService.getCancellationPeriodById(periodId);
    await cancellationPeriodService.deleteCancellationPeriod(periodId);
    await logChange({
      req, action: 'DELETE', resourceType: 'CancellationPeriod',
      resourceId: periodId.toString(),
      label: `Kündigungsfrist ${period?.description || periodId} gelöscht`,
    });
    res.json({ success: true, message: 'Kündigungsfrist gelöscht' } as ApiResponse);
  } catch (error) {
    res.status(400).json({
      success: false,
      error: error instanceof Error ? error.message : 'Fehler beim Löschen der Kündigungsfrist',
    } as ApiResponse);
  }
}
