<?php

namespace App\Observers;

use App\Enums\SaleType;
use App\Models\Sale;

class SaleObserver
{
    /**
     * Antes de crear: calcula gross_amount según sale_type.
     */
    public function creating(Sale $sale): void
    {
        $this->calculateGrossAmount($sale);
    }

    /**
     * Antes de actualizar: recalcula gross_amount y ajusta payment_status
     * si el gross_amount cambió (el observer de pagos hará el recálculo fino).
     */
    public function updating(Sale $sale): void
    {
        $this->calculateGrossAmount($sale);
    }

    private function calculateGrossAmount(Sale $sale): void
    {
        if ($sale->sale_type === SaleType::Fixed) {
            $sale->gross_amount = (float) ($sale->fixed_amount ?? 0);
        } elseif ($sale->sale_type === SaleType::Hourly) {
            $rate = (float) ($sale->hourly_rate ?? 0);
            $hrs  = (float) ($sale->hours_quantity ?? 0);
            $sale->gross_amount = round($rate * $hrs, 2);
        }
    }
}
