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

export async function getProfile(_req: AuthRequest, res: Response): Promise<void> {
  try {
    const data = await companyProfileService.getOrCreateProfile();
    res.json({ success: true, data } as ApiResponse);
  } catch (error) {
    res.status(500).json({ success: false, error: 'Fehler beim Laden der Firmendaten' } as ApiResponse);
  }
}

export async function updateProfile(req: AuthRequest, res: Response): Promise<void> {
  try {
    const updated = await companyProfileService.updateProfile(req.body ?? {});
    await logChange({
      req,
      action: 'UPDATE',
      resourceType: 'CompanyProfile',
      resourceId: updated.id.toString(),
      label: 'Firmenstammdaten (Absender) geändert',
    });
    res.json({ success: true, data: updated } as ApiResponse);
  } catch (error) {
    res.status(500).json({ success: false, error: 'Fehler beim Speichern der Firmendaten' } as ApiResponse);
  }
}
