<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('users', function (Blueprint $t) {
            $t->id();
            $t->foreignId('company_id')->constrained('companies')->cascadeOnDelete();

            $t->string('name');
            $t->string('email');
            $t->string('phone')->nullable();
            $t->string('avatar_url')->nullable();

            $t->string('role')->default('user');     // admin / manager / receptionist / mechanic / user
            $t->string('status')->default('active'); // active / inactive / blocked
            $t->string('locale', 5)->default('ro');

            $t->timestamp('email_verified_at')->nullable();
            $t->string('password');
            $t->timestamp('last_login_at')->nullable();
            $t->rememberToken();
            $t->timestamps();
            $t->softDeletes();

            // CRITIC: same email can exist across tenants but unique within tenant.
            $t->unique(['company_id', 'email']);
            $t->index(['company_id', 'role']);
            $t->index(['company_id', 'status']);
        });

        Schema::create('password_reset_tokens', function (Blueprint $t) {
            $t->string('email')->primary();
            $t->string('token');
            $t->timestamp('created_at')->nullable();
        });

        Schema::create('sessions', function (Blueprint $t) {
            $t->string('id')->primary();
            $t->foreignId('user_id')->nullable()->index();
            $t->string('ip_address', 45)->nullable();
            $t->text('user_agent')->nullable();
            $t->longText('payload');
            $t->integer('last_activity')->index();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('sessions');
        Schema::dropIfExists('password_reset_tokens');
        Schema::dropIfExists('users');
    }
};
