<?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('reviews', function (Blueprint $table) {
            $table->id();
            $table->foreignId('reviewer_id')->constrained('users')->onDelete('cascade');
            $table->foreignId('reviewee_id')->constrained('users')->onDelete('cascade');
            $table->foreignId('ad_id')->nullable()->constrained('ads')->onDelete('set null');
            $table->integer('rating')->unsigned(); // 1-5 stars (individual reviews are whole numbers)
            $table->text('review_text')->nullable();
            $table->string('ad_title')->nullable(); // Store ad title for history
            $table->string('ad_category')->nullable(); // Store category for context
            $table->enum('transaction_type', ['buyer', 'seller']); // reviewer was buyer or seller
            $table->boolean('is_verified_purchase')->default(false);
            $table->timestamps();
            $table->softDeletes();
            
            // Indexes for performance
            $table->index('reviewer_id');
            $table->index('reviewee_id');
            $table->index('rating');
            $table->index('created_at');
            
            // Prevent duplicate reviews for the same transaction
            $table->unique(['reviewer_id', 'reviewee_id', 'ad_id'], 'unique_review_per_transaction');
        });
    }

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