<?php

namespace App\Http\Controllers\Payments;

use App\Http\Controllers\Controller;
use App\Models\Deposit;
use Illuminate\Http\Request;
use Stripe\Webhook;

class StripeWebhookController extends Controller
{
    public function handle(Request $request)
    {
        $payload = $request->getContent();
        $sig     = $request->header('Stripe-Signature');

        $event = Webhook::constructEvent(
            $payload,
            $sig,
            config('services.stripe.webhook_secret')
        );

        switch ($event->type) {
            case 'payment_intent.amount_capturable_updated': {
                $pi = $event->data->object;
                $deposit = $this->findDeposit($pi);
                if ($deposit && $deposit->status !== 'requires_capture') {
                    $deposit->update([
                        'status' => 'requires_capture',
                        'deposit_confirmed_at' => now(),
                        'stripe_payment_intent_id' => $pi->id,
                    ]);
                }
                break;
            }
            case 'charge.captured':
            case 'payment_intent.succeeded': {
                $pi = $event->data->object;
                $deposit = $this->findDeposit($pi);
                if ($deposit) {
                    $deposit->update([
                        'status' => 'captured',
                        'captured_at' => now(),
                    ]);
                }
                break;
            }
            case 'payment_intent.canceled':
            case 'payment_intent.payment_failed': {
                $pi = $event->data->object;
                $deposit = $this->findDeposit($pi);
                if ($deposit) {
                    $deposit->update(['status' => 'failed']);
                }
                break;
            }
        }

        return response()->json(['ok' => true]);
    }

    private function findDeposit($pi): ?\App\Models\Deposit
    {
        $depositId = $pi->metadata->deposit_id ?? null;
        if ($depositId) return Deposit::find($depositId);
        return Deposit::where('stripe_payment_intent_id', $pi->id)->first();
    }
}
