<?php

namespace App\Http\Controllers\Api\Billing;

use App\Domains\Billing\Actions\CreateTenantBillingInvoiceAction;
use App\Domains\Billing\Models\Plan;
use App\Http\Controllers\Controller;
use App\Http\Requests\Billing\CreateTenantBillingInvoiceRequest;
use Illuminate\Http\JsonResponse;

class CreateTenantBillingInvoiceController extends Controller
{
    public function __invoke(
        CreateTenantBillingInvoiceRequest $request,
        CreateTenantBillingInvoiceAction $createTenantBillingInvoice,
    ): JsonResponse {
        $tenant = $request->user()->tenant()->firstOrFail();
        $plan = Plan::query()->findOrFail($request->validated('plan_id'));

        $invoice = $createTenantBillingInvoice->execute(
            tenant: $tenant,
            plan: $plan,
            user: $request->user(),
            billingCycle: $request->validated('billing_cycle', 'monthly'),
        );

        return response()->json([
            'data' => [
                'id' => $invoice->id,
                'invoiceNumber' => $invoice->invoice_number,
                'status' => $invoice->status,
                'amount' => '$'.number_format((float) $invoice->amount, 2),
                'checkoutUrl' => $invoice->checkout_url,
                'planName' => $invoice->plan?->name,
                'dueAt' => $invoice->due_at?->format('M d, Y'),
            ],
        ], 201);
    }
}
