<?php

namespace App\Services;

use Illuminate\Support\Facades\Storage;

class PdfCacheService
{
    private const STORAGE_DIR = 'invoices';

    private function path(string $month): string
    {
        return self::STORAGE_DIR . '/' . $month . '.json';
    }

    /**
     * Save invoice data for a month.
     * Merges with any existing data keyed by invoice ID.
     *
     * @param string $month   Format: YYYY-MM
     * @param array  $invoices  Array of invoice records (each must have an 'id' key)
     */
    public function save(string $month, array $invoices): void
    {
        $existing = $this->load($month) ?? [];

        // Index existing by id for deduplication
        $indexed = [];
        foreach ($existing as $item) {
            $key = $item['id'] ?? $item['IssuedInvoiceId'] ?? null;
            if ($key !== null) {
                $indexed[$key] = $item;
            }
        }

        foreach ($invoices as $invoice) {
            $key = $invoice['id'] ?? $invoice['IssuedInvoiceId'] ?? null;
            if ($key !== null) {
                $indexed[$key] = $invoice;
            } else {
                $indexed[] = $invoice;
            }
        }

        Storage::put($this->path($month), json_encode(array_values($indexed), JSON_PRETTY_PRINT));
    }

    /**
     * Load invoice data for a month.
     *
     * @param  string $month  Format: YYYY-MM
     * @return array|null
     */
    public function load(string $month): ?array
    {
        $path = $this->path($month);

        if (!Storage::exists($path)) {
            return null;
        }

        $content = Storage::get($path);
        $data = json_decode($content, true);

        return is_array($data) ? $data : null;
    }

    /**
     * Delete cache file for a month.
     */
    public function cleanup(string $month): void
    {
        $path = $this->path($month);

        if (Storage::exists($path)) {
            Storage::delete($path);
        }
    }

    /**
     * List all months that have a cache file.
     *
     * @return string[]
     */
    public function listMonths(): array
    {
        $files = Storage::files(self::STORAGE_DIR);
        $months = [];

        foreach ($files as $file) {
            $basename = basename($file, '.json');
            if (preg_match('/^\d{4}-\d{2}$/', $basename)) {
                $months[] = $basename;
            }
        }

        rsort($months);

        return $months;
    }
}
