<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use App\Exceptions\ImmutableFinancialDataException;

class OrderFinancialSnapshot extends Model
{
    protected $fillable = [
        'order_id',
        'customer_payment',
        'platform_commission',
        'restaurant_earning',
        'delivery_boy_earning',
        'refund_amount',
        'settlement_status',
        'snapshot_created_at',
        'is_immutable'
    ];

    protected $casts = [
        'customer_payment' => 'decimal:2',
        'platform_commission' => 'decimal:2',
        'restaurant_earning' => 'decimal:2',
        'delivery_boy_earning' => 'decimal:2',
        'refund_amount' => 'decimal:2',
        'is_immutable' => 'boolean',
        'snapshot_created_at' => 'datetime',
    ];

    public function order(): BelongsTo
    {
        return $this->belongsTo(Order::class);
    }

    public static function createFromOrder(Order $order): self
    {
        $platformCommissionRate = 0.15; // 15%
        $deliveryCommissionRate = 0.80; // 80% of delivery fee

        $customerPayment = $order->total;
        $platformCommission = $customerPayment * $platformCommissionRate;
        $deliveryBoyEarning = $order->delivery_fee * $deliveryCommissionRate;
        $restaurantEarning = $customerPayment - $platformCommission - $deliveryBoyEarning;

        return self::create([
            'order_id' => $order->id,
            'customer_payment' => $customerPayment,
            'platform_commission' => $platformCommission,
            'restaurant_earning' => $restaurantEarning,
            'delivery_boy_earning' => $deliveryBoyEarning,
            'refund_amount' => 0,
            'settlement_status' => 'pending',
            'snapshot_created_at' => now(),
            'is_immutable' => false
        ]);
    }

    public function makeImmutable(): void
    {
        $this->update(['is_immutable' => true]);
    }

    public function updateRefund(float $amount): void
    {
        if ($this->is_immutable) {
            throw new ImmutableFinancialDataException('Cannot modify immutable financial snapshot');
        }

        $this->update(['refund_amount' => $amount]);
    }

    public function updateSettlementStatus(string $status): void
    {
        if ($this->is_immutable && $status !== 'settled') {
            throw new ImmutableFinancialDataException('Cannot modify settlement status of immutable snapshot');
        }

        $this->update(['settlement_status' => $status]);
    }

    protected static function booted()
    {
        static::updating(function ($snapshot) {
            if ($snapshot->is_immutable && $snapshot->isDirty(['customer_payment', 'platform_commission', 'restaurant_earning', 'delivery_boy_earning'])) {
                throw new ImmutableFinancialDataException('Cannot modify immutable financial data');
            }
        });
    }
}