<?php

namespace App\Exports;

use App\Models\Election;
use App\Models\ElectionAuditLog;
use Illuminate\Support\Collection;

class ElectionAuditLogExport
{
    public function __construct(
        protected Election $election,
    ) {}

    /**
     * Get the audit log data as a collection of arrays suitable for CSV export.
     */
    public function getData(): Collection
    {
        return ElectionAuditLog::where('election_id', $this->election->id)
            ->with('actor:id,firstname,surname,email')
            ->orderBy('id')
            ->get()
            ->map(function (ElectionAuditLog $entry) {
                return [
                    'ID' => $entry->id,
                    'Timestamp' => $entry->created_at?->toIso8601String(),
                    'Event Type' => $entry->event_type,
                    'Actor' => $entry->actor
                        ? "{$entry->actor->firstname} {$entry->actor->surname} ({$entry->actor->email})"
                        : 'System',
                    'Actor IP' => $entry->actor_ip ?? 'N/A',
                    'Payload' => json_encode($entry->payload),
                    'Integrity Hash' => $entry->integrity_hash,
                    'Previous Hash' => $entry->previous_hash ?? 'GENESIS',
                ];
            });
    }

    /**
     * Get CSV headers.
     */
    public function getHeaders(): array
    {
        return ['ID', 'Timestamp', 'Event Type', 'Actor', 'Actor IP', 'Payload', 'Integrity Hash', 'Previous Hash'];
    }

    /**
     * Generate CSV content as a string.
     */
    public function toCsv(): string
    {
        $data = $this->getData();
        $headers = $this->getHeaders();

        $output = fopen('php://temp', 'r+');

        // Write BOM for Excel compatibility
        fwrite($output, "\xEF\xBB\xBF");

        // Write headers
        fputcsv($output, $headers);

        // Write data rows
        foreach ($data as $row) {
            fputcsv($output, $row);
        }

        rewind($output);
        $csv = stream_get_contents($output);
        fclose($output);

        return $csv;
    }

    /**
     * Get the suggested filename for the export.
     */
    public function getFilename(): string
    {
        $slug = preg_replace('/[^a-zA-Z0-9_-]/', '_', $this->election->title);
        return "election-audit-log-{$slug}-" . now()->format('Y-m-d-His') . '.csv';
    }
}
