<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->boolean('is_tenant_owner')->default(false)->after('is_admin');
        });

        DB::table('users')->whereExists(function ($query): void {
            $query->select(DB::raw(1))
                ->from('user_roles')
                ->join('roles', 'roles.id', '=', 'user_roles.role_id')
                ->whereColumn('user_roles.user_id', 'users.id')
                ->where('roles.slug', 'owner');
        })->update(['is_tenant_owner' => true]);
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('is_tenant_owner');
        });
    }
};
