<?php

namespace App\Services;

use App\Models\Booking;
use App\Models\EscrowLedger;
use App\Models\Payment;
use Illuminate\Support\Facades\DB;

class EscrowService
{
    public function recordDeposit(Payment $payment): EscrowLedger
    {
        return EscrowLedger::create([
            'booking_id' => $payment->booking_id,
            'payment_id' => $payment->id,
            'user_id' => $payment->booking->customer_id ?? null,
            'type' => 'deposit',
            'amount' => $payment->amount,
            'currency' => $payment->currency,
            'metadata' => ['status' => $payment->status],
        ]);
    }

    public function hold(Payment $payment): EscrowLedger
    {
        return EscrowLedger::create([
            'booking_id' => $payment->booking_id,
            'payment_id' => $payment->id,
            'user_id' => $payment->booking->customer_id ?? null,
            'type' => 'hold',
            'amount' => $payment->amount,
            'currency' => $payment->currency,
            'metadata' => ['status' => 'captured'],
        ]);
    }

    public function release(Booking $booking, float $amount): EscrowLedger
    {
        return EscrowLedger::create([
            'booking_id' => $booking->id,
            'user_id' => $booking->provider_id,
            'type' => 'release',
            'amount' => $amount,
            'currency' => $booking->currency,
            'metadata' => ['action' => 'release'],
        ]);
    }

    public function refund(Payment $payment, float $amount): EscrowLedger
    {
        return EscrowLedger::create([
            'booking_id' => $payment->booking_id,
            'payment_id' => $payment->id,
            'user_id' => $payment->booking->customer_id ?? null,
            'type' => 'refund',
            'amount' => $amount,
            'currency' => $payment->currency,
            'metadata' => ['action' => 'refund'],
        ]);
    }

    public function payout(Booking $booking, float $amount): EscrowLedger
    {
        return EscrowLedger::create([
            'booking_id' => $booking->id,
            'user_id' => $booking->provider_id,
            'type' => 'payout',
            'amount' => $amount,
            'currency' => $booking->currency,
            'metadata' => ['action' => 'payout'],
        ]);
    }
}
