package de.votian.services.service;

import de.votian.services.dto.JobListRowDto;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class JobListExportService {

    private static final DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm");

    public byte[] createCsv(String title, List<JobListRowDto> rows) {
        StringBuilder csv = new StringBuilder();
        csv.append(title).append("\n");
        csv.append("Auftrag;Status;Auftragszeit;Abschluss;Kunde;Kostenstelle;Kommission;Abholung;Zustellung;Kurier;Gesamtpreis;Exportiert;Fahrzeug\n");
        for (JobListRowDto row : rows) {
            csv.append(value(row.getId())).append(';')
                    .append(csvValue(statusLabel(row.getStatus()))).append(';')
                    .append(csvValue(format(row.getOrderTime()))).append(';')
                    .append(csvValue(format(row.getFinishTime()))).append(';')
                    .append(csvValue(row.getCustomerName())).append(';')
                    .append(csvValue(row.getCostCenterName())).append(';')
                    .append(csvValue(row.getCommissionNo())).append(';')
                    .append(csvValue(row.getPickupName())).append(';')
                    .append(csvValue(row.getDeliveryName())).append(';')
                    .append(csvValue(row.getCourierSid())).append(';')
                    .append(csvValue(value(row.getTotalPrice()))).append(';')
                    .append(row.isExported() ? "Ja" : "Nein").append(';')
                    .append(csvValue(vehicleLabel(row.getVehicleTypeId())))
                    .append('\n');
        }
        return csv.toString().getBytes(StandardCharsets.UTF_8);
    }

    private String statusLabel(Integer status) {
        if (status == null) {
            return "";
        }
        return switch (status) {
            case 0 -> "Blockiert";
            case 1 -> "Zugewiesen";
            case 2 -> "In Zustellung";
            case 8 -> "Zugestellt";
            case 9 -> "Abgeschlossen";
            case 10 -> "Storniert";
            default -> String.valueOf(status);
        };
    }

    private String vehicleLabel(Integer vehicleTypeId) {
        return vehicleTypeId != null ? "Typ " + vehicleTypeId : "";
    }

    private String csvValue(String value) {
        if (value == null) {
            return "";
        }
        return "\"" + value.replace("\"", "\"\"").replace("\n", " ").replace("\r", " ") + "\"";
    }

    private String value(Object value) {
        return value != null ? value.toString() : "";
    }

    private String format(LocalDateTime value) {
        return value != null ? value.format(DATE_TIME_FORMAT) : "";
    }
}
