<?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
    {
        // --- 1. Admin Roles ---
        Schema::create('admin_roles', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique(); // owner, manager, staff, viewer
            $table->string('description')->nullable();
            $table->timestamps();
        });

        // --- 2. User-Store-Role Pivot (Tenant Assignment) ---
        Schema::create('admin_user_stores', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->onDelete('cascade');
            $table->string('store_id')->index(); // 'bakery', 'fashion'
            $table->foreignId('role_id')->constrained('admin_roles');
            $table->timestamps();

            $table->unique(['user_id', 'store_id']); // One role per store per user
        });

        // --- 3. Audit Log ---
        Schema::create('audit_logs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->nullable()->constrained('users')->onDelete('set null');
            $table->string('store_id')->index();
            $table->string('action'); // e.g., 'product.updated', 'order.status_changed'
            $table->string('auditable_type')->nullable(); // Polymorphic model type
            $table->unsignedBigInteger('auditable_id')->nullable(); // Polymorphic model ID
            $table->json('old_values')->nullable();
            $table->json('new_values')->nullable();
            $table->string('ip_address', 45)->nullable();
            $table->string('user_agent')->nullable();
            $table->timestamps();

            $table->index(['auditable_type', 'auditable_id']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('audit_logs');
        Schema::dropIfExists('admin_user_stores');
        Schema::dropIfExists('admin_roles');
    }
};
