<?php

namespace App\Http\Requests;

use App\Models\Project;
use App\Services\ProjectUrlNormalizer;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;
use InvalidArgumentException;

class StoreProjectRequest extends FormRequest
{
    public function authorize(): bool { return $this->user()?->can('create', Project::class) ?? false; }
    public function rules(): array { return ['name' => ['required', 'string', 'max:150'], 'website_url' => ['required', 'string', 'max:2048']]; }
    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator): void {
            if ($validator->errors()->has('website_url')) return;
            try {
                $normalized = app(ProjectUrlNormalizer::class)->normalize((string) $this->input('website_url'));
                if ($this->user()->projects()->where('domain', $normalized->domain)->exists()) {
                    $validator->errors()->add('website_url', 'Bu alan adı hesabınızda zaten kayıtlı.');
                }
            } catch (InvalidArgumentException $exception) {
                $validator->errors()->add('website_url', $exception->getMessage());
            }
        });
    }
}
