<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    public function up(): void
    {
        $this->updatePvgisSource(
            'Ertrag mit EU PVGIS prüfen',
            'https://re.jrc.ec.europa.eu/pvg_tools/de/',
        );
    }

    public function down(): void
    {
        $this->updatePvgisSource(
            'EU PVGIS · Standortmodell prüfen',
            'https://re.jrc.ec.europa.eu/api/v5_3/PVcalc?lat=49.63&lon=6.27&peakpower=1&loss=14&optimalangles=1&outputformat=json',
        );
    }

    private function updatePvgisSource(string $label, string $url): void
    {
        $service = DB::table('services')->where('slug', 'photovoltaik')->first();

        if (! $service) {
            return;
        }

        $decision = json_decode($service->decision_content ?: '[]', true) ?: [];
        $facts = $decision['facts'] ?? [];

        foreach ($facts as &$fact) {
            if (($fact['title'] ?? '') !== 'Beispielertrag einer 5-kWp-Anlage') {
                continue;
            }

            $fact['source_label'] = $label;
            $fact['source_url'] = $url;
        }
        unset($fact);

        $decision['facts'] = $facts;

        DB::table('services')->where('id', $service->id)->update([
            'decision_content' => json_encode($decision, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            'updated_at' => now(),
        ]);
    }
};
