<?php

namespace App\Http\Controllers\Api\Cable;

use App\Core\Exceptions\InsufficientBalanceException;
use App\Core\Exceptions\ServiceException;
use App\Core\Traits\CalculatesFees;
use App\Core\Traits\GeneratesReference;
use App\Http\Controllers\Api\BaseController;
use App\Models\BillService;
use App\Models\BillVariation;
use App\Modules\ProviderIntegration\Interfaces\ProviderInterface;
use App\Modules\Transactions\Interfaces\TransactionServiceInterface;
use App\Modules\Wallet\Interfaces\WalletServiceInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class CableController extends BaseController
{
    use GeneratesReference, CalculatesFees;

    public function __construct(
        protected ProviderInterface $provider,
        protected TransactionServiceInterface $transactionService,
        protected WalletServiceInterface $walletService
    ) {}

    public function providers(): JsonResponse
    {
        $providers = BillService::active()->category('cable')->get();
        return $this->successResponse($providers);
    }

    public function bouquets(Request $request, string $provider): JsonResponse
    {
        $service = BillService::where('code', $provider)->active()->firstOrFail();

        $bouquets = BillVariation::where('bill_service_id', $service->id)
            ->active()
            ->orderBy('sort_order')
            ->get();

        return $this->successResponse([
            'provider' => $service,
            'bouquets' => $bouquets,
        ]);
    }

    public function validate(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'smartcard_number' => ['required', 'string'],
            'provider' => ['required', 'string'],
        ]);

        $service = BillService::where('code', $validated['provider'])->active()->firstOrFail();

        try {
            $response = $this->provider->validateCustomer(
                $service->code,
                $validated['smartcard_number']
            );

            return $this->successResponse([
                'valid' => true,
                'customer_data' => $response,
            ]);
        } catch (\Exception $e) {
            return $this->errorResponse('Validation failed: ' . $e->getMessage(), 422);
        }
    }

    public function purchase(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'smartcard_number' => ['required', 'string'],
            'provider' => ['required', 'string'],
            'variation_code' => ['required', 'string'],
            'amount' => ['required', 'numeric', 'min:100'],
            'phone' => ['nullable', 'string', 'max:20'],
            'subscription_type' => ['nullable', 'string', 'in:renew,change'],
            'idempotency_key' => ['nullable', 'string', 'unique:transactions,idempotency_key'],
        ]);

        $user = $request->user();
        $service = BillService::where('code', $validated['provider'])->active()->firstOrFail();
        $variation = BillVariation::where('code', $validated['variation_code'])->firstOrFail();
        $fee = $this->calculateFee($validated['amount'], (float) $service->service_charge, $service->category);
        $totalAmount = $validated['amount'] + $fee;

        if (!$this->checkDailyTransactionLimit($user->id)) {
            throw new ServiceException('Daily transaction limit reached. Please try again tomorrow.', 'DAILY_LIMIT', 422);
        }

        try {
            DB::beginTransaction();

            if (!$this->walletService->canDebit($user->id, $totalAmount)) {
                throw new InsufficientBalanceException();
            }

            $reference = self::generateReference('CBL');
            $idempotencyKey = $validated['idempotency_key'] ?? (string) Str::uuid();

            $transaction = $this->transactionService->createTransaction([
                'user_id' => $user->id,
                'reference' => $reference,
                'bill_service_id' => $service->id,
                'bill_variation_id' => $variation->id,
                'type' => 'cable',
                'service_name' => $service->name . ' - ' . $variation->name,
                'network' => $service->code,
                'customer_number' => $validated['smartcard_number'],
                'amount' => $validated['amount'],
                'fee' => $fee,
                'total_amount' => $totalAmount,
                'ip_address' => $request->ip(),
                'device' => $request->userAgent(),
                'idempotency_key' => $idempotencyKey,
            ]);

            $this->walletService->debitWallet(
                $user->id,
                $totalAmount,
                "Cable subscription - {$service->name} ({$variation->name})",
                $reference,
                'transaction',
                $transaction->id
            );

            $this->transactionService->markProcessing($reference);

            DB::commit();

            $requestId = self::generateVTPassRequestId();

            try {
                $response = $this->provider->purchaseCable(
                    $validated['smartcard_number'],
                    $service->code,
                    $validated['variation_code'],
                    $validated['subscription_type'] ?? 'renew',
                    $validated['amount'],
                    $validated['phone'] ?? $user->phone ?? '',
                    $requestId
                );

                if (isset($response['code']) && $response['code'] === '000') {
                    $this->transactionService->markSuccessful($reference, $response);
                } else {
                    $this->transactionService->markFailed(
                        $reference,
                        $response['response_description'] ?? 'Purchase failed',
                        $response
                    );
                    $this->refundWalletOnFailure($user->id, $totalAmount, $reference);
                }
            } catch (\Exception $e) {
                $this->transactionService->markFailed($reference, $e->getMessage(), []);
                $this->refundWalletOnFailure($user->id, $totalAmount, $reference);
            }

            $transaction = $this->transactionService->getTransaction($user->id, $reference);

            return $this->successResponse($transaction, 'Cable subscription submitted');
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }

    protected function refundWalletOnFailure(string $userId, float $amount, string $reference): void
    {
        $this->walletService->refundWallet(
            $userId,
            $amount,
            "Refund for failed cable purchase {$reference}",
            'RFD-' . strtoupper(Str::random(8)),
            'transaction',
            null
        );
    }
}
