<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    public $connection = 'sizes_db';

    public function up(): void
    {
        // Jika belum ada tabel di sizes_db, buat dan coba salin data dari DB utama jika ada
        if (!Schema::connection($this->connection)->hasTable('product_sizes')) {
            Schema::connection($this->connection)->create('product_sizes', function (Blueprint $table) {
                $table->id();
                $table->unsignedBigInteger('product_id')->index();
                $table->string('size');
                $table->integer('stock')->default(0);
                $table->timestamps();
            });

            // Jika ada data di DB default, salin ke sizes_db (opsional)
            try {
                $rows = DB::connection(config('database.default'))->table('product_sizes')->get();
                foreach ($rows as $r) {
                    DB::connection($this->connection)->table('product_sizes')->insert([
                        'id' => $r->id,
                        'product_id' => $r->product_id,
                        'size' => $r->size,
                        'stock' => $r->stock,
                        'created_at' => $r->created_at,
                        'updated_at' => $r->updated_at,
                    ]);
                }
            } catch (\Exception $e) {
                // Abaikan jika tabel lama tidak ada atau terjadi masalah
            }
        }
    }

    public function down(): void
    {
        Schema::connection($this->connection)->dropIfExists('product_sizes');
    }
};
