<?php

namespace App\Master\Http\Requests;

use App\Models\ContentSync;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Http\FormRequest;

class ContentSyncDataRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        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))
                ->where(fn ($q) => $q->whereNull('approval_status')
                    ->orWhere('approval_status', ContentSync::APPROVAL_APPROVED))
                ->exists();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
        ];
    }


    /**
     * @return ContentSync|Model
     */
    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))
            ->where(fn ($q) => $q->whereNull('approval_status')
                ->orWhere('approval_status', ContentSync::APPROVAL_APPROVED))
            ->firstOrFail();
    }
}
