<?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('accounts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('company', 255)->nullable();
            $table->string('employee_count', 20)->nullable();
            $table->string('email', 255)->nullable();
            $table->string('type', 45);
            $table->string('phone', 20)->nullable();
            $table->string('phone_prefix', 10)->nullable();
            $table->string('website_url', 255)->nullable();
            $table->string('tax_id', 45)->nullable();

            $table->unsignedBigInteger('owner_id')->nullable();
            $table->unsignedBigInteger('address_id')->nullable();
            $table->unsignedBigInteger('billing_address_id')->nullable();
            $table->timestamps();

            $table->foreign('owner_id')->references('id')
                ->on('users')->onDelete('RESTRICT')->onUpdate('CASCADE');
            $table->foreign('address_id')->references('id')
                ->on('addresses')->onDelete('SET NULL')->onUpdate('CASCADE');
            $table->foreign('billing_address_id')->references('id')
                ->on('addresses')->onDelete('SET NULL')->onUpdate('CASCADE');
        });

        Schema::create('account_members', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('account_id');
            $table->unsignedBigInteger('user_id')->nullable();
            $table->string('invitation_first_name', 45)->nullable();
            $table->string('invitation_last_name', 45)->nullable();
            $table->string('invitation_email', 255)->nullable();
            $table->boolean('is_admin')->default(false);
            $table->string('status', 20);
            $table->string('token', 255)->nullable();
            $table->timestamp('accepted_at')->nullable();
            $table->timestamps();

            $table->foreign('account_id')->references('id')
                ->on('accounts')->onDelete('CASCADE')->onUpdate('CASCADE');
            $table->foreign('user_id')->references('id')
                ->on('users')->onDelete('CASCADE')->onUpdate('CASCADE');
        });
    }

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