<?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
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('sale_details', function (Blueprint $table) {
            $table->unsignedBigInteger('membership_user_id')->nullable()->after('product_id');
            $table->foreign('membership_user_id')
                ->references('id')
                ->on('membership_users');
        });

        // Allow sale details to represent either a product or a membership purchase.
        DB::statement('ALTER TABLE sale_details MODIFY product_id BIGINT UNSIGNED NULL');

        // Enforce exactly one source per detail: product OR membership_user.
        DB::statement(
            'ALTER TABLE sale_details ADD CONSTRAINT chk_sale_details_item_source '
            . 'CHECK ((product_id IS NOT NULL AND membership_user_id IS NULL) '
            . 'OR (product_id IS NULL AND membership_user_id IS NOT NULL))'
        );
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('sale_details', function (Blueprint $table) {
            $table->dropForeign(['membership_user_id']);
            $table->dropColumn('membership_user_id');
        });

        DB::statement('ALTER TABLE sale_details DROP CHECK chk_sale_details_item_source');
        DB::statement('ALTER TABLE sale_details MODIFY product_id BIGINT UNSIGNED NOT NULL');
    }
};
