<?php

namespace App\Http\Controllers\Concerns;

use App\Models\Organization;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

trait HandlesWidgetCors
{
    protected function originAllowed(Organization $organization, ?string $origin): bool
    {
        $allowedOrigins = collect(preg_split('/[\r\n,]+/', (string) $organization->widget_allowed_origins))
            ->map(fn (string $value) => trim($value))
            ->filter();

        return $allowedOrigins->isEmpty()
            || ($origin !== null && $allowedOrigins->contains($origin));
    }

    protected function jsonWithCors(Request $request, JsonResponse $response, ?Organization $organization = null, string $methods = 'GET, POST, OPTIONS'): JsonResponse
    {
        $origin = $request->headers->get('origin');
        $allowOrigin = '*';

        if ($organization !== null && $origin !== null && $this->originAllowed($organization, $origin)) {
            $allowOrigin = $origin;
        }

        $response->headers->set('Access-Control-Allow-Origin', $allowOrigin);
        $response->headers->set('Access-Control-Allow-Methods', $methods);
        $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept');
        $response->headers->set('Vary', 'Origin');

        return $response;
    }
}
