<?php

use A7kz\Platform\Models\UniModel;
use A7kz\Platform\Modules\Platform\Core\Facades\Core;
use A7kz\Platform\Modules\Platform\Segment\Facades\Segment;
use Carbon\Carbon;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use \A7kz\Platform\Commands\InstallScript;
use JetBrains\PhpStorm\NoReturn;

return new class extends \A7kz\Platform\Commands\InstallScript {

    public function install($module_name, $module_version)
    {
    }

    public function update($module_name, $module_version): void
    {
        $this->upgrade();
        $this->seed();
    }

    #[NoReturn] private function seed(): void
    {
        $seed = Storage::disk('pipicar_crm')->get('auto/seeds/seed.json');

        if (str_starts_with($seed, "\xef\xbb\xbf")) {
            $seed = substr($seed, 3); // Удаляем первые 3 байта
        }

        $data = json_decode($seed, true);

        $segments = Segment::listActive();

        $count = UniModel::model('pipi_auto')->count();

        if ($count === 0) {
            foreach ($segments as $segment) {
                foreach ($data as $value) {
                    if ($value['ПометкаУдаления'] == 'Нет') {
                        $car = UniModel::model('pipi_auto', $segment->connector);
                        $car->guid = $value['СсылкаGUID'];
                        $car->code = $value['Код'];
                        $car->name = $value['Наименование'];
                        $car->type_id = UniModel::model('pipi_auto_types', $segment->connector)
                            ->firstOrCreate([
                                'name' => $value['Тип']
                            ])->id;
                        $car->class_id = UniModel::model('pipi_auto_classes', $segment->connector)
                            ->firstOrCreate([
                                'name' => $value['Класс']
                            ])->id;
                        $autoBrand = UniModel::model('pipi_auto_brands', $segment->connector)
                            ->firstOrCreate([
                                'name' => $value['Марка']
                            ]);
                        $car->brand_id = $autoBrand->id;
                        $car->model_id = UniModel::model('pipi_brand_models', $segment->connector)
                            ->firstOrCreate([
                                'name'      => $value['Модель'],
                                'brand_id'  => $autoBrand->id,
                                'year'      => $this->formatDate($value['ГодПроизводства'])?->format('Y'),
                            ])->id;
                        $car->color_id = UniModel::model('pipi_auto_colors', $segment->connector)
                            ->firstOrCreate([
                                'name' => $value['Цвет']
                            ])->id;
                        $car->serial_number = $value['СерийныйНомер'];
                        $car->state_number = $value['ГосНомер'];
                        $car->manufacture_year = $this->formatDate($value['ГодПроизводства'])?->format('Y-m-d');
                        $car->passport_number = $value['НомерТехПаспорта'];
                        $car->passport_date = $this->formatDate($value['ДатаТехпаспорта'])?->format('Y-m-d');
                        $car->estimated_cost = $value['ОценочнаяСтоимость'];
                        $owner = UniModel::model('pipi_owners', $segment->connector)
                            ->firstOrCreate([
                                'name' =>$value['ВладелецИмущества']
                            ]);
                        $car->owner_id = $owner->id;
                        $car->is_trust_management = (bool) $value['ВДоверенномУправлении'];
                        $car->owner_percentage = $value['ПроцентВладельца'];
                        $car->owner_contract = $owner->contract_file_path;
                        $car->is_inactive = (bool) $value['НеИспользовать'];
                        $car->is_predefined = (bool) $value['Предопределенный'];
                        $car->predefined_data_name = $value['ИмяПредопределенныхДанных'];
                        $car->inspection_kit = json_validate($value['КомпректацияДляОсмотра']) ? $value['КомпректацияДляОсмотра'] : null;
                        $car->save();
                    }
                }
            }
        }
    }

    private function upgrade(): void
    {
        $segments = Segment::listActive();
        foreach ($segments as $segment) {
            if (!Schema::connection($segment->connector)->hasTable('pipi_auto')) {
                Schema::connection($segment->connector)->create('pipi_auto', static function (Blueprint $table) {
                    $table->id();
                    $table->string('code')->unique()->comment('Код');
                    $table->string('name')->nullable()->comment('Наименование');
                    $table->unsignedBigInteger('type_id')->nullable()->comment('Тип');
                    $table->unsignedBigInteger('class_id')->nullable()->comment('Класс');
                    $table->unsignedBigInteger('brand_id')->nullable()->comment('Марка');
                    $table->unsignedBigInteger('model_id')->nullable()->comment('Модель');
                    $table->unsignedBigInteger('color_id')->nullable()->comment('Цвет');
                    $table->string('serial_number')->nullable()->comment('Серийный номер');
                    $table->string('state_number')->nullable()->comment('Госномер');
                    $table->date('manufacture_year')->nullable()->comment('Год производства');
                    $table->string('passport_number')->nullable()->comment('Номер техпаспорта');
                    $table->date('passport_date')->nullable()->comment('Дата техпаспорта');
                    $table->float('estimated_cost')->nullable()->comment('Оценочная стоимость');
                    $table->unsignedBigInteger('owner_id')->nullable()->comment('Владелец имущества');
                    $table->boolean('is_trust_management')->default(false)->comment('В доверенном управлении');
                    $table->integer('owner_percentage')->nullable()->comment('Процент владельца');
                    $table->string('owner_contract')->nullable()->comment('Договор владельца имущества');
                    $table->boolean('is_inactive')->default(false)->comment('Не использовать');
                    $table->json('inspection_kit')->nullable()->comment('Комплектация для осмотра');
                    $table->boolean('is_predefined')->default(false)->comment('Предопределенный');
                    $table->string('predefined_data_name')->nullable()->comment('Имя предопределенных данных');
                    $table->timestamps();
                    $table->softDeletes();

                    // Внешние ключи
                    $table->foreign('type_id')->references('id')->on('pipi_auto_types');
                    $table->foreign('class_id')->references('id')->on('pipi_auto_classes');
                    $table->foreign('brand_id')->references('id')->on('pipi_auto_brands');
                    $table->foreign('model_id')->references('id')->on('pipi_brand_models');
                    $table->foreign('color_id')->references('id')->on('pipi_auto_colors');
                    $table->foreign('owner_id')->references('id')->on('pipi_owners');
                });
            }

            if (!Schema::connection($segment->connector)->hasColumn('pipi_auto', 'guid')) {
                Schema::connection($segment->connector)->table('pipi_auto', static function (Blueprint $table) {
                    $table->string('guid')->unique()->nullable();
                });
            }

            if (!Schema::connection($segment->connector)->hasColumn('pipi_auto', 'photo_id')) {
                Schema::connection($segment->connector)->table('pipi_auto', static function (Blueprint $table) {
                    $table->unsignedBigInteger('photo_id')->nullable();
                });
            }

            if (!Schema::connection($segment->connector)->hasColumn('pipi_auto', 'regular_user')) {
                Schema::connection($segment->connector)->table('pipi_auto', static function (Blueprint $table) {
                    $table->unsignedBigInteger('regular_user')->nullable();
                });
            }
        }
    }

    private function formatDate($date): ?Carbon
    {
        $date = trim($date);

        try {
            return Carbon::parse($date);
        } catch (\Exception $e) {
            return null;
        }
    }
};
