<?php

declare(strict_types=1);

namespace App\Application\Campaign;

use App\Framework\Attributes\Route;
use App\Framework\Http\Method;
use App\Framework\Http\Request;
use App\Framework\Http\Responses\Redirect;

/**
 * Subscribe to Campaign Email Notifications
 *
 * Handles email collection for release notifications
 */
final readonly class SubscribeCampaign
{
    public function __construct(
        private CampaignService $campaignService
    ) {
    }

    #[Route(path: '/campaign/{slug}/subscribe', method: Method::POST)]
    public function __invoke(string $slug, Request $request): Redirect
    {

        // Fetch campaign
        $campaign = $this->campaignService->findBySlug($slug);

        if (! $campaign) {
            return Redirect::to('/404')
                ->withFlash('error', 'Campaign not found');
        }

        // Validate email
        $email = $request->parsedBody->get('email');
        $name = $request->parsedBody->get('name');
        $newsletter = $request->parsedBody->get('newsletter') === '1';

        if (! $email || ! filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return Redirect::back()
                ->withFlash('error', 'Please provide a valid email address')
                ->withInput($request->parsedBody->toArray());
        }

        // Record subscription
        try {
            $this->campaignService->recordEmailSubscription(
                $campaign->id,
                $email,
                $name,
                $newsletter
            );

            return Redirect::to("/campaign/{$slug}/success")
                ->withFlash('success', "You'll receive an email when {$campaign->album_title} is released!");
        } catch (\Exception $e) {
            return Redirect::back()
                ->withFlash('error', 'Failed to subscribe. Please try again.')
                ->withInput($request->parsedBody->toArray());
        }
    }
}
