<?php

namespace App\Http\Controllers\Api\Marketing;

use App\Http\Controllers\Controller;
use App\Models\GiftVoucher;
use App\Services\GiftVouchers\GiftVoucherService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class GiftVoucherResendController extends Controller
{
    public function __construct(private readonly GiftVoucherService $vouchers) {}

    public function __invoke(Request $request): JsonResponse
    {
        $data = $request->validate([
            'code' => ['required', 'string'],
            'recipient_only' => ['sometimes', 'boolean'],
            'locale' => ['nullable', 'string'],
            'schedule_at' => ['nullable', 'date'],
        ]);

        $voucher = GiftVoucher::query()
            ->where('code', strtoupper($data['code']))
            ->first();

        if (! $voucher) {
            throw ValidationException::withMessages([
                'code' => __('Voucher not found.'),
            ]);
        }

        if (! empty($data['schedule_at'])) {
            $this->vouchers->scheduleRecipientDelivery($voucher, now()->parse($data['schedule_at']), $data['locale'] ?? app()->getLocale());
        } else {
            $this->vouchers->resend($voucher, $data['locale'] ?? app()->getLocale(), $data['recipient_only'] ?? null);
        }

        return response()->json([
            'status' => 'ok',
        ]);
    }
}
