// ==================== FIRMENSTAMMDATEN (ABSENDER) ====================
// Einzel-Zeile. Fließt in Gutschrift-PDF + ZUGFeRD-XML (Verkäufer) ein.

import prisma from '../lib/prisma.js';
import { Prisma } from '@prisma/client';

const EDITABLE_STRING_FIELDS = [
  'name', 'street', 'houseNumber', 'postalCode', 'city', 'country',
  'vatId', 'taxNumber', 'commercialRegister', 'managingDirector',
  'email', 'phone', 'website', 'iban', 'bic', 'bankName',
] as const;

export async function getOrCreateProfile() {
  const existing = await prisma.companyProfile.findFirst();
  if (existing) return existing;
  return prisma.companyProfile.create({ data: {} });
}

export async function updateProfile(input: Record<string, unknown>) {
  const profile = await getOrCreateProfile();
  const data: Prisma.CompanyProfileUpdateInput = {};
  for (const field of EDITABLE_STRING_FIELDS) {
    if (typeof input[field] === 'string') {
      (data as Record<string, unknown>)[field] = (input[field] as string).slice(0, 191).trim();
    }
  }
  return prisma.companyProfile.update({ where: { id: profile.id }, data });
}
