<?php

namespace App\Http\Controllers\Api\Transaction;

use App\Http\Controllers\Api\BaseController;
use App\Models\Receipt;
use App\Models\Transaction;
use App\Modules\Transactions\Interfaces\TransactionServiceInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class TransactionController extends BaseController
{
    public function __construct(
        protected TransactionServiceInterface $transactionService
    ) {}

    public function index(Request $request): JsonResponse
    {
        $transactions = $this->transactionService->getUserTransactions(
            $request->user()->id,
            $request->get('per_page', 15),
            $request->get('type'),
            $request->get('status')
        );

        return $this->paginatedResponse($transactions);
    }

    public function show(Request $request, string $reference): JsonResponse
    {
        $transaction = $this->transactionService->getTransaction($request->user()->id, $reference);
        return $this->successResponse($transaction);
    }

    public function receipt(Request $request, string $reference): JsonResponse
    {
        $transaction = $this->transactionService->getTransaction($request->user()->id, $reference);

        $receipt = Receipt::where('transaction_id', $transaction->id)->first();

        if (!$receipt) {
            $receipt = Receipt::create([
                'user_id' => $request->user()->id,
                'transaction_id' => $transaction->id,
                'receipt_number' => Receipt::generateReceiptNumber(),
                'data' => [
                    'reference' => $transaction->reference,
                    'service' => $transaction->service_name,
                    'amount' => $transaction->amount,
                    'fee' => $transaction->fee,
                    'total' => $transaction->total_amount,
                    'status' => $transaction->status,
                    'date' => $transaction->created_at->toDateTimeString(),
                    'customer' => $transaction->customer_number,
                ],
            ]);
        }

        return $this->successResponse([
            'receipt' => $receipt,
            'transaction' => $transaction,
        ]);
    }
}
