<?php

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

/**
 * Searchable index of the products contained in each public "share link"
 * (one row in `shared_products`). The share link itself stores its products as
 * a denormalised JSON blob (`shared_products.products_data`) which is not
 * queryable, and carries no category. This table flattens that blob into one
 * row per product and resolves each SKU to its product / category so the
 * Activity Log can filter share links by product name, SKU, or category.
 *
 * Populated by:
 *   - Modules\ActivityLog\Entities\Services\SharedLinkIndexer (live, on new shares)
 *   - php artisan activitylog:backfill-shared-links (one-time, existing shares)
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('shared_product_items', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('shared_product_id')->index();
            $table->unsignedInteger('business_id')->nullable()->index();
            $table->unsignedBigInteger('product_id')->nullable()->index();
            $table->string('sku', 191)->nullable()->index();
            $table->string('product_name', 255)->nullable();
            $table->unsignedInteger('category_id')->nullable();
            $table->unsignedInteger('sub_category_id')->nullable();

            // Category filtering is always scoped to a business.
            $table->index(['business_id', 'category_id']);
            $table->index(['business_id', 'sub_category_id']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('shared_product_items');
    }
};
