<?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
    {
        // Eliminar tablas del sistema anterior
        Schema::dropIfExists('upwork_transactions');
        Schema::dropIfExists('upwork_sync_logs');

        // Nueva tabla: pagos semanales de Upwork (EarningsOverview)
        Schema::create('upwork_earnings', function (Blueprint $table) {
            $table->id();

            $table->date('date_from');                   // Inicio del período de trabajo
            $table->date('date_to');                     // Fin del período de trabajo

            $table->string('team_name');                 // "NUNA TECH"
            $table->string('team_upwork_id')->nullable();// "0z3n_ol1c7gjdpee4tvmia"

            $table->string('contract_title');            // "PHP and WordPress Web Developer"
            $table->string('contract_upwork_id');        // "41811519"

            $table->decimal('amount', 12, 2);
            $table->string('payment_type')->nullable();

            // Links opcionales a entidades de Nuna
            $table->foreignId('client_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('sale_id')->nullable()->constrained()->nullOnDelete();

            $table->foreignId('imported_by_user_id')->constrained('users')->restrictOnDelete();
            $table->timestamp('imported_at')->useCurrent();

            $table->timestamps();

            // Evita duplicados: mismo contrato + misma semana
            $table->unique(['contract_upwork_id', 'date_from', 'date_to'], 'upwork_earnings_unique');

            $table->index('date_from');
            $table->index('contract_upwork_id');
        });
    }

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