<?php

use Illuminate\Database\Migrations\Migration;
use Inside\Notify\Models\Notification;
use Inside\Notify\Models\NotificationType;
use Inside\Permission\Models\Role;

class FixOldReportNotifications extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        /** @var \Inside\Notify\Models\NotificationType[] $types */
        $types = NotificationType::where('action', 'report')->get();

        foreach ($types as $type) {
            $keepNotifsIds = Notification::where('notification_type_id', $type->id)
                ->pluck('id', 'notifiable_uuid')
                ->unique();

            Notification::where('notification_type_id', $type->id)
                ->whereNotIn('id', $keepNotifsIds)
                ->delete();

            Notification::whereIn('id', $keepNotifsIds)->each(function ($notif) {
                $notif->user_uuid = null;
                $notif->author_uuid = $notif->data['from'] ?? null;
                $notif->save();
            });
        }
    }
}
