<?php

namespace MasterStudy\Lms\Http\Controllers\Course;

use MasterStudy\Lms\Http\Serializers\CourseListSerializer;
use MasterStudy\Lms\Http\WpResponseFactory;
use MasterStudy\Lms\Repositories\CourseRepository;
use MasterStudy\Lms\Validation\Validator;
use WP_REST_Request;
use WP_REST_Response;

final class GetAdminCoursesController {
	public function __invoke( WP_REST_Request $request ): WP_REST_Response {
		$validator = new Validator(
			$request->get_params(),
			array(
				'per_page'   => 'nullable|integer',
				'page'       => 'nullable|integer',
				'search'     => 'nullable|string',
				'category'   => 'nullable|string',
				'lesson_id'  => 'nullable|integer',
				'quiz_id'    => 'nullable|integer',
				'google_meet_id' => 'nullable|integer',
				'status'     => 'nullable|string|contains_list,any;publish;pending;draft;trash;private',
				'sort'       => 'nullable|string',
				'date_range' => 'nullable|string',
			)
		);

		if ( $validator->fails() ) {
			return WpResponseFactory::validation_failed( $validator->get_errors_array() );
		}

		$data            = ( new CourseRepository() )->get_admin_list( $validator->get_validated() );
		$data['courses'] = ( new CourseListSerializer() )->collectionToArray( $data['posts'] );
		unset( $data['posts'] );

		return new WP_REST_Response( $data );
	}
}
