<?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('sales', function (Blueprint $table) {
            $table->id();

            $table->foreignId('client_id')->constrained()->restrictOnDelete();
            $table->foreignId('owner_user_id')->constrained('users')->restrictOnDelete();
            $table->foreignId('created_by_user_id')->constrained('users')->restrictOnDelete();

            $table->enum('origin', ['manual', 'upwork', 'renovacion'])->default('manual');
            $table->enum('sale_type', ['fixed', 'hourly'])->default('fixed');

            $table->string('title');
            $table->text('description')->nullable();

            $table->date('sale_date');
            $table->enum('currency', ['USD', 'BOB'])->default('USD');

            $table->decimal('fixed_amount', 12, 2)->nullable();
            $table->decimal('hourly_rate', 10, 2)->nullable();
            $table->decimal('hours_quantity', 8, 2)->nullable();

            $table->decimal('gross_amount', 12, 2)->default(0);
            $table->decimal('collected_amount_cached', 12, 2)->default(0);

            $table->enum('payment_status', ['unpaid', 'partial', 'paid'])->default('unpaid');

            $table->date('expected_collect_date')->nullable();
            $table->string('expected_collect_note')->nullable();

            $table->date('last_follow_up_date')->nullable();
            $table->text('follow_up_note')->nullable();

            $table->string('external_source')->nullable();
            $table->string('external_id')->nullable();

            $table->timestamps();

            $table->index('client_id');
            $table->index('owner_user_id');
            $table->index('payment_status');
            $table->index('sale_date');
            $table->index('expected_collect_date');
            $table->index('currency');
            $table->index(['external_source', 'external_id']);
        });
    }

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