<?php

namespace App\Http\Requests;

use App\Models\ContentSync;
use App\Repositories\SiteExportRepository;
use Carbon\Carbon;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class SiteExportRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     * Uses same token validation as ContentSync
     */
    public function authorize(): bool
    {
        return $this->hasHeader('x-token')
            && $this->hasHeader('x-user')
            && ContentSync::query()
                ->where('token', $this->header('x-token'))
                ->whereHas('user', fn ($query) => $query->where('email', $this->header('x-user')))
                ->where('created_at', '>=', Carbon::now()->subMinutes(ContentSync::TTL))
                ->exists();
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'modules' => ['sometimes', 'array'],
            'modules.*' => ['string', Rule::in(array_keys(SiteExportRepository::MODULES))],
            'page' => ['sometimes', 'integer', 'min:1'],
            'path' => ['sometimes', 'string'],
        ];
    }

    /**
     * Get the ContentSync record associated with this request
     */
    public function sync(): ContentSync
    {
        return ContentSync::query()
            ->where('token', $this->header('x-token'))
            ->whereHas('user', fn ($query) => $query->where('email', $this->header('x-user')))
            ->where('created_at', '>=', Carbon::now()->subMinutes(ContentSync::TTL))
            ->firstOrFail();
    }

    /**
     * Get the authentication token for encrypting secrets
     */
    public function getEncryptionKey(): string
    {
        return $this->header('x-token');
    }
}
