import { Response } from 'express';
import { ApiResponse, AuthRequest } from '../types/index.js';
import { logChange } from '../services/audit.service.js';
import * as blzData from '../services/blzData.service.js';

// Status der BLZ-/Bankdaten (installierte Version, Quelle, Auto-Update-Stand).
export async function getStatus(req: AuthRequest, res: Response): Promise<void> {
  try {
    const status = await blzData.getStatus();
    res.json({ success: true, data: status } as ApiResponse);
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error instanceof Error ? error.message : 'Fehler beim Laden des BLZ-Status',
    } as ApiResponse);
  }
}

// Jetzt prüfen/aktualisieren (manueller Trigger). ?force=1 lädt auch bei
// gleicher Version neu.
export async function updateNow(req: AuthRequest, res: Response): Promise<void> {
  try {
    const force = req.query.force === '1' || req.query.force === 'true';
    const result = await blzData.runUpdate(force);
    await logChange({
      req,
      action: 'UPDATE',
      resourceType: 'AppSetting',
      resourceId: 'blz-data',
      label: `BLZ-Bankdaten: ${result.message}`,
    });
    const status = await blzData.getStatus();
    res.json({ success: true, data: { result, status } } as ApiResponse);
  } catch (error) {
    res.status(502).json({
      success: false,
      error: error instanceof Error ? error.message : 'BLZ-Aktualisierung fehlgeschlagen',
    } as ApiResponse);
  }
}
