<?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('collection_visits', function (Blueprint $table) {
            $table->id();
            $table->foreignId('company_id')->constrained()->cascadeOnDelete();
            $table->foreignId('credit_id')->constrained()->cascadeOnDelete();
            $table->foreignId('installment_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('collector_user_id')->constrained('users')->cascadeOnDelete();

            // Tipo de visita
            $table->enum('visit_type', ['no_payment', 'follow_up', 'promise', 'other'])
                ->default('no_payment');

            // Motivo del no pago
            $table->enum('reason', [
                'not_home',        // No estaba en casa
                'no_money',        // Sin dinero
                'will_pay_later',  // Pide volver después
                'refused',         // Rechazó pagar
                'partial_promise', // Promete pago parcial
                'other',            // Otro
            ])->nullable();

            $table->text('notes')->nullable();

            // Promesa de pago
            $table->date('promised_date')->nullable();
            $table->decimal('promised_amount', 12, 2)->nullable();

            // Fecha y hora de la visita
            $table->date('visit_date');
            $table->time('visit_time')->nullable();

            // Geolocalización
            $table->decimal('latitude', 10, 7)->nullable();
            $table->decimal('longitude', 10, 7)->nullable();

            // PWA sync support
            $table->string('device_id', 255)->nullable();
            $table->uuid('idempotency_key')->nullable()->unique();

            $table->timestamps();

            // Índices para búsquedas comunes
            $table->index(['company_id', 'visit_date'], 'visits_company_date_idx');
            $table->index(['collector_user_id', 'visit_date'], 'visits_collector_date_idx');
            $table->index(['credit_id', 'visit_date'], 'visits_credit_date_idx');
            $table->index(['company_id', 'idempotency_key'], 'visits_company_idempotency_idx');
        });
    }

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