<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Inside\Content\Facades\Schema as InsideSchema;
use Inside\Host\Migrations\CreateContentTypes;
use Inside\Notify\Models\Notification;
use Inside\Notify\Models\NotificationType;

final class DeletePAndPFeature extends Migration
{
    use CreateContentTypes;

    public function up(): void
    {
        $this->bootUp(__FILE__);

        $types = collect([
            'p_and_p',
            'p_and_p_regions',
            'p_and_p_categories',
            'p_and_p_types',
        ]);

        $notificationsActions = [
            'p_and_p_region_created',
            'p_and_p_region_assigned',
            'p_and_p_region_changed',
            'p_and_p_updated',
            'p_and_p_updated_manager',
            'p_and_p_published',
        ];

        NotificationType::query()
            ->whereIn('action', $notificationsActions)
            ->orWhereIn('model', $types->map(fn (string $type) => type_to_class($type)))
            ->delete();

        Notification::query()
            ->whereIn('notifiable_type', $types->map(fn (string $type) => type_to_class($type)))
            ->delete();

        $types
            ->filter(fn (string $type) => InsideSchema::hasModel($type))
            ->each(function (string $type) {
                $this->getBridge()?->contentTypeDelete($type);
            });

        Schema::dropIfExists('desk_p_and_p_contacts');

        // In case bugging ¯\_(ツ)_/¯
        Schema::dropIfExists('inside_content_p_and_p');

        DB::table('node')
            ->whereIn('type', $types)
            ->delete();

        DB::table('inside_models')
            ->whereIn('class', $types->map(fn (string $type) => type_to_class($type)))
            ->delete();

        $this->finishUp();
    }
}
