import { FastifyInstance } from "fastify"
import { historyitems } from "../../db/schema";

const HISTORY_ENTITY_LABELS: Record<string, string> = {
    customers: "Kunden",
    contracts: "Verträge",
    members: "Mitglieder",
    vendors: "Lieferanten",
    projects: "Projekte",
    plants: "Objekte",
    contacts: "Kontakte",
    inventoryitems: "Inventarartikel",
    customerinventoryitems: "Kundeninventar",
    products: "Artikel",
    profiles: "Mitarbeiter",
    absencerequests: "Abwesenheiten",
    events: "Termine",
    tasks: "Aufgaben",
    vehicles: "Fahrzeuge",
    costcentres: "Kostenstellen",
    ownaccounts: "zusätzliche Buchungskonten",
    documentboxes: "Dokumentenboxen",
    hourrates: "Stundensätze",
    services: "Leistungen",
    roles: "Rollen",
    checks: "Überprüfungen",
    spaces: "Lagerplätze",
    customerspaces: "Kundenlagerplätze",
    trackingtrips: "Fahrten",
    createddocuments: "Dokumente",
    inventoryitemgroups: "Inventarartikelgruppen",
    bankstatements: "Buchungen",
    incominginvoices: "Eingangsrechnungen",
    files: "Dateien",
    memberrelations: "Mitgliedsverhältnisse",
    teams: "Teams",
    outgoingsepamandates: "Ausgehende SEPA-Mandate",
}

export function getHistoryEntityLabel(entity: string) {
    return HISTORY_ENTITY_LABELS[entity] || entity
}

export async function insertHistoryItem(
    server: FastifyInstance,
    params: {
        tenant_id: number
        created_by: string | null
        entity: string
        entityId: string | number
        action: "created" | "updated" | "unchanged" | "deleted" | "archived"
        oldVal?: any
        newVal?: any
        text?: string
    }
) {
    const entityLabel = getHistoryEntityLabel(params.entity)
    const textMap = {
        created: `Neuer Eintrag in ${entityLabel} erstellt`,
        updated: `Eintrag in ${entityLabel} geändert`,
        unchanged: `Eintrag in ${entityLabel} unverändert`,
        archived: `Eintrag in ${entityLabel} archiviert`,
        deleted: `Eintrag in ${entityLabel} gelöscht`
    }

    const columnMap: Record<string, string> = {
        customers: "customer",
        contracts: "contract",
        members: "customer",
        vendors: "vendor",
        projects: "project",
        plants: "plant",
        contacts: "contact",
        inventoryitems: "inventoryitem",
        products: "product",
        profiles: "profile",
        absencerequests: "absencerequest",
        events: "event",
        tasks: "task",
        vehicles: "vehicle",
        costcentres: "costcentre",
        ownaccounts: "ownaccount",
        documentboxes: "documentbox",
        hourrates: "hourrate",
        services: "service",
        roles: "role",
        checks: "check",
        spaces: "space",
        customerspaces: "customerspace",
        customerinventoryitems: "customerinventoryitem",
        trackingtrips: "trackingtrip",
        createddocuments: "createddocument",
        inventoryitemgroups: "inventoryitemgroup",
        bankstatements: "bankstatement",
        incominginvoices: "incomingInvoice",
        files: "file",
        memberrelations: "memberrelation",
        outgoingsepamandates: "outgoingsepamandate",
    }

    const fkColumn = columnMap[params.entity]
    if (!fkColumn) {
        server.log.warn(`Keine History-Spalte für Entity: ${params.entity}`)
        return
    }

    const stringifyHistoryValue = (value: any) => {
        if (value === undefined || value === null) return null
        return typeof value === "string" ? value : JSON.stringify(value)
    }

    const entry = {
        tenant: params.tenant_id,
        createdBy: params.created_by,
        text: params.text || textMap[params.action],
        action: params.action,
        [fkColumn]: params.entityId,
        oldVal: stringifyHistoryValue(params.oldVal),
        newVal: stringifyHistoryValue(params.newVal)
    }

    await server.db.insert(historyitems).values(entry as any)
}
