<?php

use App\Enum\Dsar\DsarStatus;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

/**
 * Some tranches were left on status 'draft' after their DSARs had already gone
 * out. Tranche deletion is guarded by "only draft tranches can be deleted", so
 * those stuck rows made it possible to delete sent DSARs.
 *
 * Any draft tranche holding at least one DSAR past the pre-send stage is moved
 * to 'sent', which is the status Tranche\View::sendBatch() would have set.
 */
return new class extends Migration {
    public function up(): void {
        $preSend      = DsarStatus::preSend();
        $placeholders = implode(',', array_fill(0, count($preSend), '?'));

        DB::update("
            UPDATE dsar_tranches t
            SET t.status = 'sent'
            WHERE t.status = 'draft'
              AND EXISTS (
                  SELECT 1 FROM dsars d
                  WHERE d.tranche_id = t.id
                    AND d.deleted_at IS NULL
                    AND d.status NOT IN ({$placeholders})
              )
        ", $preSend);
    }

    public function down(): void {
        // Cannot distinguish backfilled rows from tranches legitimately sent. No-op.
    }
};
