<?php
declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;

class VideoFavouritesTable extends Table
{
	public function initialize(array $config): void
	{
		parent::initialize($config);

		$this->setTable('video_favourite');
		$this->setPrimaryKey('id');

		$this->belongsTo('Videos', [
			'foreignKey' => 'video_id',
		]);

		$this->belongsTo('Users', [
			'foreignKey' => 'user_id',
			'fields' => USER_FIELDS,
		]);
	}

	public function getDetails(int $id): ?array
	{
		return $this->find()
			->where(['VideoFavourites.id' => $id])
			->enableHydration(false)
			->first();
	}

	public function getUserVideoFavourites(int $user_id): array
	{
		return $this->find()
			->select(['VideoFavourites.video_id'])
			->where(['VideoFavourites.user_id' => $user_id])
			->enableHydration(false)
			->all()
			->toList();
	}

	public function getFavVideosCount(int $video_id): int
	{
		return $this->find()
			->where(['VideoFavourites.video_id' => $video_id])
			->count();
	}

	public function getUserFavouriteVideos(int $user_id, int $starting_point): array
	{
		return $this->find()
			->contain(['Videos'])
			->where([
				'VideoFavourites.user_id' => $user_id,
				'Videos.id >' => 0,
			])
			->limit(10)
			->offset($starting_point * 10)
			->enableHydration(false)
			->all()
			->toList();
	}

	public function getUserFavouriteVideosAdmin(int $user_id): array
	{
		return $this->find()
			->contain(['Videos.Users'])
			->where(['VideoFavourites.user_id' => $user_id])
			->enableHydration(false)
			->all()
			->toList();
	}

	public function ifExist(array $data): ?array
	{
		return $this->find()
			->where([
				'VideoFavourites.video_id' => $data['video_id'],
				'VideoFavourites.user_id' => $data['user_id'],
			])
			->enableHydration(false)
			->first();
	}

	public function getAll(): array
	{
		return $this->find()
			->enableHydration(false)
			->all()
			->toList();
	}
}
