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

export async function getTariffs(req: Request, res: Response): Promise<void> {
  try {
    const providerId = parseInt(req.params.providerId);
    const includeInactive = req.query.includeInactive === 'true';
    const tariffs = await tariffService.getTariffsByProvider(providerId, includeInactive);
    res.json({ success: true, data: tariffs } as ApiResponse);
  } catch (error) {
    res.status(500).json({
      success: false,
      error: 'Fehler beim Laden der Tarife',
    } as ApiResponse);
  }
}

export async function getTariff(req: Request, res: Response): Promise<void> {
  try {
    const tariff = await tariffService.getTariffById(parseInt(req.params.id));
    if (!tariff) {
      res.status(404).json({
        success: false,
        error: 'Tarif nicht gefunden',
      } as ApiResponse);
      return;
    }
    res.json({ success: true, data: tariff } as ApiResponse);
  } catch (error) {
    res.status(500).json({
      success: false,
      error: 'Fehler beim Laden des Tarifs',
    } as ApiResponse);
  }
}

export async function createTariff(req: Request, res: Response): Promise<void> {
  try {
    const providerId = parseInt(req.params.providerId);
    const tariff = await tariffService.createTariff({ ...req.body, providerId });
    await logChange({
      req, action: 'CREATE', resourceType: 'Tariff',
      resourceId: tariff.id.toString(),
      label: `Tarif ${tariff.name} angelegt`,
    });
    res.status(201).json({ success: true, data: tariff } as ApiResponse);
  } catch (error) {
    res.status(400).json({
      success: false,
      error: error instanceof Error ? error.message : 'Fehler beim Erstellen des Tarifs',
    } as ApiResponse);
  }
}

export async function updateTariff(req: Request, res: Response): Promise<void> {
  try {
    // Pentest R110: Mass-Assignment-Whitelist (nur name/isActive).
    const tariff = await tariffService.updateTariff(parseInt(req.params.id), pickTariffUpdate(req.body));
    await logChange({
      req, action: 'UPDATE', resourceType: 'Tariff',
      resourceId: tariff.id.toString(),
      label: `Tarif ${tariff.name} aktualisiert`,
    });
    res.json({ success: true, data: tariff } as ApiResponse);
  } catch (error) {
    res.status(400).json({
      success: false,
      error: error instanceof Error ? error.message : 'Fehler beim Aktualisieren des Tarifs',
    } as ApiResponse);
  }
}

export async function deleteTariff(req: Request, res: Response): Promise<void> {
  try {
    const tariffId = parseInt(req.params.id);
    const tariff = await tariffService.getTariffById(tariffId);
    await tariffService.deleteTariff(tariffId);
    await logChange({
      req, action: 'DELETE', resourceType: 'Tariff',
      resourceId: tariffId.toString(),
      label: `Tarif ${tariff?.name || tariffId} gelöscht`,
    });
    res.json({ success: true, message: 'Tarif gelöscht' } as ApiResponse);
  } catch (error) {
    res.status(400).json({
      success: false,
      error: error instanceof Error ? error.message : 'Fehler beim Löschen des Tarifs',
    } as ApiResponse);
  }
}
