<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Helpdesk\HelpdeskAuthorizationPolicy;
use MintyPHP\Module\Helpdesk\Service\DomainListService;
use MintyPHP\Service\Export\ExportColumn;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requireAbilityOrForbidden(HelpdeskAuthorizationPolicy::ABILITY_ACCESS);
exportRequireGetRequest();

$request = requestInput();
$session = app(SessionStoreInterface::class)->all();
$tenantId = (int) ($session['current_tenant']['id'] ?? 0);

$filters = gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php');
$filters['limit'] = exportCapLimit($request->query('limit'), 5000);
$filters['offset'] = 0;

$result = app(DomainListService::class)->query($tenantId, $filters);

$levelLabels = [
    'niedrig' => t('Low'),
    'normal' => t('Normal'),
    'hoch' => t('High'),
    'kritisch' => t('Critical'),
];

$columns = [
    new ExportColumn(t('No.'), static fn (array $row): string => (string) ($row['No'] ?? '')),
    new ExportColumn(t('Customer No.'), static fn (array $row): string => (string) ($row['Customer_No'] ?? '')),
    new ExportColumn(t('Customer Name'), static fn (array $row): string => (string) ($row['Customer_Name'] ?? '')),
    new ExportColumn(t('URL'), static fn (array $row): string => (string) ($row['URL'] ?? '')),
    new ExportColumn(t('Contract type'), static fn (array $row): string => (string) ($row['contract_type'] ?? '')),
    new ExportColumn(t('Contract No.'), static fn (array $row): string => (string) ($row['contract_no'] ?? '')),
    new ExportColumn(t('State'), static fn (array $row): string => (string) ($row['State'] ?? '')),
    new ExportColumn(t('Administration'), static fn (array $row): string => (string) ($row['Administration'] ?? '')),
    new ExportColumn(t('Security level'), static function (array $row) use ($levelLabels): string {
        $level = (string) ($row['security_level'] ?? 'normal');
        return (string) ($levelLabels[$level] ?? $level);
    }),
    new ExportColumn(t('Note'), static fn (array $row): string => (string) ($row['security_level_note'] ?? '')),
];

$filename = 'helpdesk-domains-' . date('Ymd-His') . '.csv';

exportSendCsv($filename, $result['rows'], $columns, exportResolveFlavor($request));
