<?php

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('account_supplier', function (Blueprint $table) {
			$table->timestamps();
			$table->integer('supplier_id')->unsigned();
			$table->integer('account_id')->unsigned();
			$table->string('supplier_ref');
			$table->boolean('active')->default(FALSE);

			$table->unique(['account_id','supplier_id']);
			$table->unique(['supplier_id','supplier_ref']);

			$table->foreign('account_id')->references('id')->on('accounts');
			$table->foreign('supplier_id')->references('id')->on('suppliers');
		});

		foreach (DB::table('supplier_user')->cursor() as $o) {
			$ao = \App\Models\Account::where('user_id',$o->user_id)->firstOrfail();

			DB::table('account_supplier')
				->insert([
					'created_at' => $o->created_at,
					'updated_at' => $o->updated_at,
					'supplier_id' => $o->supplier_id,
					'account_id' => $ao->id,
					'supplier_ref' => $o->supplier_ref,
					'active' => $o->active,
				]);
		}

		Schema::drop('supplier_user');
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        abort(500,'Cant go back');
    }
};