<?php

use App\Models\Enums\GrowthPetAffectEnum;
use App\Models\Enums\GrowthPetPointEnum;
use App\Models\Enums\GrowthPetTypeEnum;
use App\Models\Game\Player\GrowthPetSkillProto;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('growth_pet_skill_proto', function (Blueprint $table) {
            $table->integer('dwPetVnum');
            $table->integer('dwSkillVnum');
            $table->string('szName', 32);
            $table->enum('bType', array_column(GrowthPetTypeEnum::cases(), 'value'));
            $table->integer('dwCooldown')->length(3);

            $table->enum('setAffectFlag', array_column(GrowthPetAffectEnum::cases(), 'value'))->nullable();

            $table->enum('szPointOn', array_column(GrowthPetPointEnum::cases(), 'value'))->nullable();

            $table->string('szPointPoly1', 100);
            $table->string('szPointPoly2', 100);
            $table->string('szPointPoly3', 100);
            $table->string('szPointPoly4', 100);
            $table->string('szPointPoly5', 100);
            $table->string('szPointPoly6', 100);
            $table->string('szPointPoly7', 100);
            $table->string('szPointPoly8', 100);
            $table->string('szActivatePctPoly', 100);
            $table->string('szDurationPoly', 100);

            $table->primary(['dwPetVnum', 'dwSkillVnum']);
        });

        // Populate the table data
        $data = File::json(database_path('data/growth_pet_skill_proto.json'));

        GrowthPetSkillProto::upsert(
            collect($data)->flatMap(function ($skills, $petVnum) {
                return collect($skills)->map(function ($skill) use ($petVnum) {
                    $skill['dwPetVnum'] = $petVnum;
                    $skill = [
                        ...$skill,
                        ...collect(array_pad($skill['pointPoly'], 8, 0))
                            ->mapWithKeys(fn ($val, $key) => ['szPointPoly'.($key + 1) => $val])
                            ->toArray(),
                    ];
                    unset($skill['pointPoly']);

                    return $skill;
                });
            })->toArray(),
            ['dwPetVnum', 'dwSkillVnum']
        );
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('growth_pet_skill_proto');
    }
};
