<?php

namespace App\Classes\Modules\Affiliate\ControllersLogic;

use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Affiliate\Services\CreatesAffiliate;
use App\Classes\Modules\Affiliate\DataTransferObjects\AffiliateObject;
use App\Classes\Modules\Affiliate\Standards\Rules\CanCreateAffiliate;
use App\Http\Resources\AffiliateResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CreateAffiliateLogic extends AbstractControllerLogic
{
    /**
     * @return array
     */
    protected function notification(): array
    {
        return [
            'title' => 'Created Affiliate',
            'message' => 'You have successfully created a new Affiliate Code'
        ];
    }

    /** @var CanCreateAffiliate */
    private $canCreateAffiliate;

    /** @var CreatesAffiliate */
    private $createsAffiliate;

    /**
     * CreateAffiliateLogic constructor.
     * @param CanCreateAffiliate $canCreateAffiliate
     * @param CreatesAffiliate $createsAffiliate
     */
    public function __construct(
        CanCreateAffiliate $canCreateAffiliate,
        CreatesAffiliate $createsAffiliate
    )
    {
        $this->canCreateAffiliate = $canCreateAffiliate;
        $this->createsAffiliate = $createsAffiliate;
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Classes\Exceptions\AccessForbiddenException
     * @throws \App\Classes\Exceptions\RequestValidationException
     */
    public function logic(Request $request): JsonResponse
    {
        $code = $request->input('code');
        $code = $code !== null ? (string) $code : '';
        
        $isActive = $request->input('is_active', true);
        // Convert string 'true'/'false' to boolean if needed
        if (is_string($isActive)) {
            $isActive = filter_var($isActive, FILTER_VALIDATE_BOOLEAN);
        }
        $isActive = (bool) $isActive;

        $object = new AffiliateObject(
            $code,
            $request->input('campaign_name'),
            $request->input('campaign_description'),
            $isActive
        );

        // Validate the affiliate object
        $this->canCreateAffiliate->passes($object);

        // Create the affiliate
        $affiliate = $this->createsAffiliate->execute($object);

        return $this->resourceResponse(new AffiliateResource($affiliate));
    }
}

