<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // First, convert existing subject strings to JSON format
        $mailings = DB::table('mailings')->get();

        foreach ($mailings as $mailing) {
            if ($mailing->subject && !$this->isJson($mailing->subject)) {
                // Convert existing string subject to JSON with base language
                $subjectJson = [
                    timebank_config('base_language', 'en') => $mailing->subject
                ];

                DB::table('mailings')
                    ->where('id', $mailing->id)
                    ->update(['subject' => json_encode($subjectJson)]);
            }
        }

        // Then modify the column type
        Schema::table('mailings', function (Blueprint $table) {
            $table->json('subject')->change();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Convert JSON subjects back to strings (base language only)
        $mailings = DB::table('mailings')->get();

        foreach ($mailings as $mailing) {
            if ($mailing->subject && $this->isJson($mailing->subject)) {
                $subjectArray = json_decode($mailing->subject, true);
                $baseLanguage = timebank_config('base_language', 'en');
                $subjectString = $subjectArray[$baseLanguage] ?? array_values($subjectArray)[0] ?? '';

                DB::table('mailings')
                    ->where('id', $mailing->id)
                    ->update(['subject' => $subjectString]);
            }
        }

        Schema::table('mailings', function (Blueprint $table) {
            $table->string('subject', 255)->change();
        });
    }

    /**
     * Check if a string is valid JSON
     */
    private function isJson($string): bool
    {
        json_decode($string);
        return json_last_error() === JSON_ERROR_NONE;
    }
};
