import { Request, Response } from 'express';
import * as contractHistoryService from '../services/contractHistory.service.js';
import { logChange } from '../services/audit.service.js';
import { ApiResponse, AuthRequest } from '../types/index.js';
import { canAccessContract } from '../utils/accessControl.js';

export async function getHistoryEntries(req: AuthRequest, res: Response): Promise<void> {
  try {
    const contractId = parseInt(req.params.contractId);
    if (!(await canAccessContract(req, res, contractId))) return;
    const entries = await contractHistoryService.getHistoryEntries(contractId);
    res.json({ success: true, data: entries } as ApiResponse);
  } catch (error) {
    res.status(500).json({
      success: false,
      error: 'Fehler beim Laden der Historie',
    } as ApiResponse);
  }
}

export async function createHistoryEntry(req: AuthRequest, res: Response): Promise<void> {
  try {
    const contractId = parseInt(req.params.contractId);
    if (!(await canAccessContract(req, res, contractId))) return;
    const { title, description } = req.body;

    if (!title || typeof title !== 'string' || title.trim().length === 0) {
      res.status(400).json({
        success: false,
        error: 'Titel ist erforderlich',
      } as ApiResponse);
      return;
    }

    const entry = await contractHistoryService.createHistoryEntry(contractId, {
      title: title.trim(),
      description: description?.trim() || undefined,
      isAutomatic: false,
      createdBy: req.user?.email || 'unbekannt',
    });

    await logChange({
      req, action: 'CREATE', resourceType: 'ContractHistory',
      resourceId: entry.id.toString(),
      label: `Historieneintrag "${title.trim()}" erstellt für Vertrag #${contractId}`,
    });

    res.status(201).json({ success: true, data: entry } as ApiResponse);
  } catch (error) {
    res.status(400).json({
      success: false,
      error: error instanceof Error ? error.message : 'Fehler beim Erstellen des Eintrags',
    } as ApiResponse);
  }
}

export async function updateHistoryEntry(req: AuthRequest, res: Response): Promise<void> {
  try {
    const contractId = parseInt(req.params.contractId);
    if (!(await canAccessContract(req, res, contractId))) return;
    const entryId = parseInt(req.params.entryId);
    const { title, description } = req.body;

    const entry = await contractHistoryService.updateHistoryEntry(contractId, entryId, {
      title: title?.trim(),
      description: description?.trim(),
    });

    await logChange({
      req, action: 'UPDATE', resourceType: 'ContractHistory',
      resourceId: entryId.toString(),
      label: `Historieneintrag aktualisiert für Vertrag #${contractId}`,
    });

    res.json({ success: true, data: entry } as ApiResponse);
  } catch (error) {
    res.status(400).json({
      success: false,
      error: error instanceof Error ? error.message : 'Fehler beim Aktualisieren des Eintrags',
    } as ApiResponse);
  }
}

export async function deleteHistoryEntry(req: AuthRequest, res: Response): Promise<void> {
  try {
    const contractId = parseInt(req.params.contractId);
    if (!(await canAccessContract(req, res, contractId))) return;
    const entryId = parseInt(req.params.entryId);

    await contractHistoryService.deleteHistoryEntry(contractId, entryId);

    await logChange({
      req, action: 'DELETE', resourceType: 'ContractHistory',
      resourceId: entryId.toString(),
      label: `Historieneintrag gelöscht für Vertrag #${contractId}`,
    });

    res.json({ success: true, message: 'Eintrag gelöscht' } as ApiResponse);
  } catch (error) {
    res.status(400).json({
      success: false,
      error: error instanceof Error ? error.message : 'Fehler beim Löschen des Eintrags',
    } as ApiResponse);
  }
}
