<?php

namespace App\Classes\Modules\Affiliate\Standards\Validators;

use App\Classes\General\Abstracts\AbstractValidation;
use App\Classes\Modules\Affiliate\DataTransferObjects\AffiliateObject;
use App\Models\Affiliate;
use Illuminate\Validation\Rule;

class AffiliateCreateValidation extends AbstractValidation
{
    /**
     * @param AffiliateObject $object
     * @return array
     */
    protected function data($object): array
    {
        return [
            'code' => $object->getCode(),
            'campaign_name' => $object->getCampaignName(),
            'campaign_description' => $object->getCampaignDescription(),
            'is_active' => $object->getIsActive(),
        ];
    }

    /**
     * @return array
     */
    protected function rules(): array
    {
        return [
            'code' => [
                'nullable',
                'string',
                'min:3',
                'max:255',
                'regex:/^[a-zA-Z0-9_-]+$/',
                function ($attribute, $value, $fail) {
                    if (!empty($value)) {
                        $uppercaseCode = strtoupper($value);
                        $exists = Affiliate::whereRaw('UPPER(code) = ?', [$uppercaseCode])
                            ->whereNull('deleted_at')
                            ->exists();
                        
                        if ($exists) {
                            $fail('Affiliate code already exists. Please choose a different code.');
                        }
                    }
                },
            ],
            'campaign_name' => 'required|string|max:255',
            'campaign_description' => 'nullable|string|max:65535',
            'is_active' => 'required|boolean',
        ];
    }

    /**
     * @return array
     */
    protected function messages(): array
    {
        return [
            'code.regex' => 'The affiliate code may only contain letters, numbers, hyphens, and underscores.',
            'code.min' => 'The affiliate code must be at least 3 characters.',
            'campaign_name.required' => 'A campaign name is required.',
            'campaign_name.max' => 'The campaign name cannot exceed 255 characters.',
        ];
    }
}
