<?php

use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;

/**
 * PRC-170 SEC-Critical — encrypt payment_gateway_settings.value at rest.
 *
 * Same retroactive pattern as PRC-169 / 171 / 176. Iterates rows via raw
 * query builder (bypassing the new accessor/mutator), detects already-
 * encrypted values, encrypts plaintext. Idempotent. value column is
 * already TEXT (sufficient size for Crypt envelope).
 */
return new class extends Migration
{
    public function up(): void
    {
        $rows = DB::table('payment_gateway_settings')->select('id', 'value')->get();

        foreach ($rows as $row) {
            if ($row->value === null || $row->value === '') {
                continue;
            }
            try {
                Crypt::decryptString($row->value);
                continue; // already encrypted
            } catch (DecryptException $e) {
                // plaintext — encrypt
            }
            DB::table('payment_gateway_settings')
                ->where('id', $row->id)
                ->update([
                    'value' => Crypt::encryptString($row->value),
                    'updated_at' => now(),
                ]);
        }
    }

    public function down(): void
    {
        $rows = DB::table('payment_gateway_settings')->select('id', 'value')->get();

        foreach ($rows as $row) {
            if ($row->value === null || $row->value === '') {
                continue;
            }
            try {
                $plain = Crypt::decryptString($row->value);
            } catch (DecryptException $e) {
                continue; // already plaintext
            }
            DB::table('payment_gateway_settings')
                ->where('id', $row->id)
                ->update([
                    'value' => $plain,
                    'updated_at' => now(),
                ]);
        }
    }
};
