use Yii;
use yii\rest\Controller;
use yii\filters\auth\AuthInterface;
use yii\filters\Cors;
use yii\filters\ContentNegotiator;
use yii\filters\HTTPBearerAuth;
////use yii\filters\RateLimiter;

final class BehaviorController extends Controller

	public function behaviors(): array
	{
		$behaviors = parent::behaviors();
		
		//$behaviors['rateLimiter'] = [];
		
		/**
		* CORS Filter
		* @url https://www.yiiframework.com/doc/api/2.0/yii-filters-cors
		*
		* Handles Cross-Origin Resource Sharing headers and preflight OPTIONS requests.
		* This enables your API to accept requests from other domains (origins).
		* Must be placed BEFORE authentication so preflight OPTIONS requests are NOT blocked.
		*
		* Note: CORS filter must be before the Authenticator behavior
		*/
		$behaviors['corsFilter'] =
		[
			'class' => Cors::class,
			'cors' =>
			[
				/**
				* Allowed domains/origins that can access your API. 
				* '*' allows all origins (not recommended for production).
				*
				* 'Origin' => ['http://www.myserver.com', 'https://www.myserver.com'],
				*/
				//'Origin' => $this->getAllowedOrigins(),
				'Origin' => ['http://localhost:1234'],
				
				/**
				* HTTP methods that browsers are allowed to use when accessing your API.
				* Adjust this list according to your API specification.
				*
				* 'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
				*/
				'Access-Control-Request-Method' => ['GET', 'POST', 'OPTIONS'],
				
				// CSRF validation is ON by default, for POST requests coming from form or AJAX
				// To send CSRF token, Yii2 uses header 'X-CSRF-Token' or param '_csrf'
				
				/**
				* Allowed HTTP headers clients can use during the actual requests.
				* This should include Authorization for bearer tokens and other headers you expect.
				*
				* Common headers your React app will send are:
				*
				* - Authorization (for Bearer token)
				*	- Your backend CORS must allow both 'Authorization' and 'Content-Type' in Access-Control-Allow-Headers.
				* 	- Also, 'OPTIONS' requests must bypass authentication for CORS preflight 
				*	  (see 'except' => ['options'] in authenticator behavior).
				* - Content-Type (usually application/json)
				* - X-Requested-With (sometimes added by libraries)
				* - X-CSRF-Token (if using CSRF protection, mostly for stateful apps)
				* - Accept (To ask API which format it supports) Often handled automatically, usually no CORS action needed
				*/
				'Access-Control-Allow-Headers' => ['Authorization', 'Content-Type', 'X-Requested-With', 'X-CSRF-Token'],
				
				// Allow credentials (cookies, authorization headers, etc.) to be exposed to the browser
				'Access-Control-Allow-Credentials' => true,
				
				// Allow OPTIONS caching
				'Access-Control-Max-Age' => 3600,// 86400 - 24 hours
			],
		];
		
		/**
		* Content Negotiation
		* @url https://www.yiiframework.com/doc/api/2.0/yii-filters-contentnegotiator
		*
		* Note: Content Negotiation needs to be after CORS filer to ensure responses are JSON
		*/
		$behaviors['contentNegotiator'] =
		[
			'class' => ContentNegotiator::class,
			'formats' => [
				'application/json' => Response::FORMAT_JSON,
			],
		];
		
		/**
		* Authorization:
		* React app must include this header *after* login/sign-up, for every 
		* authenticated request (fetch, axios).
		* 
		* Example:
		*
		* 	fetch('https://api.yoursite.com/v1/account', {
		*		method: 'GET',
		* 		headers: {
		* 			'Authorization': `Bearer ${token}`,// Bearer token for authentication
		* 			'Content-Type': 'application/json'
		* 		}
		* 	})
		*	.then(response => response.json())
		*	.then(data => {
		*		console.log('User profile:', data);
		*	}).catch(console.error);
		*
		* Note: Authentication filter comes after CORS filter and Content Negotiator
		*/
		$behaviors['authenticator'] =
		[
			'class' => JwtHttpBearerAuth::class,
			'except' => ['options', 'login', 'signup'],// exclude OPTIONS explicitly here too
		];
	}
	
	/**
	* ENV and CORS Origins
	* Fetch allowed origins from env variable
	* Assume your .env has: ALLOWED_ORIGINS=https://example.com,http://localhost:3000
	*/
	protected function getAllowedOrigins(): array
	{
		$originsEnv = $_ENV['CORS_ORIGINS'] ?? getenv('CORS_ORIGINS') ?: '';
		
		// Split into array, trim whitespace, remove empties
		$origins = array_filter(array_map('trim', explode(',', $originsEnv)));
		if (empty($origins))
		{
			// default origin for dev, adjust accordingly
			$origins = ['http://localhost:1234'];
		}
		
		return $origins;
	}
	
since majority of my controllers will be using the same cors and content negotiation, and with some minor differences in the acess-control... could I not
write a controller that is called as a extend, so than I dont need to add these to each?