<?php

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

/**
 * PRC-254 — encrypt client_products.password at rest, same pattern as
 * PRC-169 (servers.password): widen column to TEXT, encrypt any rows
 * still in plaintext via raw DB::table (bypasses the new mutator).
 * Already-encrypted rows are detected by attempting decrypt and left alone.
 * Idempotent.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('client_products', function (Blueprint $table) {
            $table->text('password')->nullable()->change();
        });

        $rows = DB::table('client_products')->select('id', 'password')->get();

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

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

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

        Schema::table('client_products', function (Blueprint $table) {
            $table->string('password')->nullable()->change();
        });
    }
};
