<?php

namespace App\Services\Checkout;

use App\Models\CheckoutSession;
use App\Models\Tenant;
use LogicException;

class CheckoutPaymentService
{
    public function __construct(
        private readonly CheckoutSessionService $sessions,
        private readonly CheckoutAssignmentService $assignment,
    ) {}

    public function initialiseStripe(CheckoutSession $session, array $payload = []): array
    {
        if ($session->provider !== CheckoutSession::PROVIDER_STRIPE) {
            $this->sessions->selectProvider($session, CheckoutSession::PROVIDER_STRIPE);
        }

        // TODO: integrate Stripe PaymentIntent creation and return client_secret + publishable key
        return [
            'session_id' => $session->id,
            'status' => $session->status,
            'message' => 'Stripe integration pending implementation.',
        ];
    }

    public function confirmStripe(CheckoutSession $session, array $payload = []): CheckoutSession
    {
        if ($session->provider !== CheckoutSession::PROVIDER_STRIPE) {
            throw new LogicException('Cannot confirm Stripe payment on a non-Stripe session.');
        }

        // TODO: verify PaymentIntent status with Stripe SDK and update session metadata
        $this->sessions->markProcessing($session);

        return $session;
    }

    public function finaliseFree(CheckoutSession $session): CheckoutSession
    {
        if ($session->provider !== CheckoutSession::PROVIDER_FREE) {
            $this->sessions->selectProvider($session, CheckoutSession::PROVIDER_FREE);
        }

        $this->sessions->markProcessing($session);
        $this->assignment->finalise($session, ['source' => 'free']);

        return $this->sessions->markCompleted($session);
    }

    public function attachTenantAndResume(CheckoutSession $session, Tenant $tenant): CheckoutSession
    {
        $this->sessions->attachTenant($session, $tenant);
        $this->sessions->refreshExpiration($session);

        return $session;
    }
}
