<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('upwork_transactions', function (Blueprint $table) {
            $table->id();

            // ── Datos de Upwork ───────────────────────────────────────────────
            $table->date('transaction_date');
            $table->string('transaction_id')->unique(); // Ref ID de Upwork
            $table->string('transaction_type');         // Hourly, Fixed-price, Service Fee, Withdrawal…

            $table->string('job_title')->nullable();    // Transaction summary
            $table->string('period_detail')->nullable(); // "Earnings for Feb 9-Feb 15, 2026"
            $table->date('period_start')->nullable();   // parseado de period_detail
            $table->date('period_end')->nullable();     // parseado de period_detail

            $table->string('client_team')->nullable();  // nombre del cliente en Upwork
            $table->string('freelancer')->nullable();
            $table->string('agency_team')->nullable();
            $table->string('account_name')->nullable(); // cuenta Upwork (TWIITI SRL / Jes Pardo)
            $table->string('payment_method')->nullable();
            $table->text('description')->nullable();    // Description 1+2+3 concatenados

            $table->decimal('amount_usd', 12, 2)->default(0);
            $table->decimal('current_balance', 10, 2)->nullable();

            // ── Matching con Nuna ─────────────────────────────────────────────
            $table->foreignId('client_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('sale_id')->nullable()->constrained()->nullOnDelete();

            // ── Descarte manual ───────────────────────────────────────────────
            $table->boolean('discarded')->default(false);
            $table->timestamp('discarded_at')->nullable();
            $table->foreignId('discarded_by_user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->text('discard_reason')->nullable();

            $table->timestamps();

            $table->index('transaction_date');
            $table->index('transaction_type');
            $table->index('client_team');
            $table->index('discarded');
        });
    }

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