<?php

use Illuminate\Database\Migrations\Migration;
use Inside\Content\Models\Contents\PAndP;
use Inside\Content\Models\Contents\PAndPRegions;
use Inside\Content\Models\Contents\RegionalOffices;
use Inside\Host\Bridge\BridgeContent;
use Inside\Host\Bridge\BridgeContentType;

class FixRegionalOfficesTranslations extends Migration
{
    /**
     * @throws Exception
     */
    public function up(): void
    {
        $bridge = new BridgeContent();

        $regions = PAndPRegions::query()
            ->doesntHave('regionalOffices')
            ->get()
            ->each(function (PAndPRegions $region) use ($bridge) {
                $bridge->contentDelete($region->content_type, $region->uuid);
            })
        ;

        $offices = RegionalOffices::query()
            ->select(['*'])
            ->selectRaw('COUNT(uuid_host) as occurence')
            ->groupBy('uuid_host')
            ->having('occurence', '=', 1)
            ->get()
            ->each(function (RegionalOffices $office) use ($bridge) {
                $bridge->contentUpdate($office->content_type, ['uuid' => $office->uuid, 'langcode' => env('APP_LOCALE')]);
            })
        ;

        $offices = RegionalOffices::query()
            ->where('status', 1)
            ->where('langcode', '=', env('APP_LOCALE'))
            ->doesntHave('reversePAndPRegions')
            ->get()
        ;

        if ($offices->isEmpty()) {
            return;
        }

        $pAndPs = PAndP::query()->where('langcode', env('APP_LOCALE'))->where('status', 1)->get();

        $offices->each(function (RegionalOffices $office) use ($pAndPs, $bridge) {
            foreach ($pAndPs as $content) {
                $bridge->contentInsert('p_and_p_regions', [
                    'langcode' => env('APP_LOCALE'),
                    'type' => 'node',
                    'bundle' => 'p_and_p_regions',
                    'title' => $content->title . ' : ' . $office->title,
                    'p_and_p' => [$content->uuid],
                    'regional_offices' => [$office->uuid],
                ]);
            }
        });
    }

    public function down(): void
    {
    }
}
