<?php

namespace App\Http\Controllers\Api\Marketing;

use App\Http\Controllers\Controller;
use App\Models\Package;
use App\Services\Coupons\CouponService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;

class CouponPreviewController extends Controller
{
    public function __construct(private readonly CouponService $coupons) {}

    public function __invoke(Request $request): JsonResponse
    {
        $data = $request->validate([
            'code' => ['required', 'string', 'max:64'],
            'package_id' => ['required', 'integer', 'exists:packages,id'],
        ]);

        $package = Package::findOrFail($data['package_id']);

        if (! $package->paddle_price_id) {
            throw ValidationException::withMessages([
                'code' => __('marketing.coupon.errors.package_not_configured'),
            ]);
        }

        $tenant = Auth::user()?->tenant;

        try {
            $preview = $this->coupons->preview($data['code'], $package, $tenant);
        } catch (ValidationException $exception) {
            Log::warning('Coupon preview denied', [
                'code' => $data['code'],
                'package_id' => $package->id,
                'tenant_id' => $tenant?->id,
                'errors' => $exception->errors(),
            ]);

            throw $exception;
        }

        Log::info('Coupon preview success', [
            'code' => $preview['coupon']->code,
            'package_id' => $package->id,
            'tenant_id' => $tenant?->id,
            'discount' => $preview['pricing']['discount'] ?? null,
        ]);

        return response()->json([
            'coupon' => [
                'id' => $preview['coupon']->id,
                'code' => $preview['coupon']->code,
                'type' => $preview['coupon']->type?->value,
                'amount' => (float) $preview['coupon']->amount,
                'currency' => $preview['coupon']->currency,
                'description' => $preview['coupon']->description,
                'expires_at' => $preview['coupon']->ends_at?->toIso8601String(),
                'is_stackable' => $preview['coupon']->is_stackable,
            ],
            'pricing' => $preview['pricing'],
            'package' => [
                'id' => $package->id,
                'name' => $package->name,
                'price' => (float) $package->price,
                'currency' => $package->currency ?? 'EUR',
            ],
            'source' => $preview['source'],
        ]);
    }
}
