<?php

namespace Planaday\Api\Mock;

use DateTime;
use Planaday\Entities\Voucher\DTO\Voucher;
use Planaday\Entities\Voucher\Exception\VoucherNotFoundException;
use Planaday\Entities\Voucher\VoucherApi;
use Planaday\Entities\Voucher\VoucherType;
use Planaday\Utility\Debug\Log\Logging;

class MockVoucherApi implements VoucherApi {
	use Logging;
	protected VoucherApi|null $voucherApiMock = null;
	protected array $vouchers = [];

	public function __construct() {
		$this->createVouchers();
	}

	public function getVoucher( string $code ): Voucher {
		$this->logInfo("Getting voucher $code");
		if ($this->voucherApiMock !== null) return $this->voucherApiMock->getVoucher($code);

		if (isset($this->vouchers[$code])) {
			$this->logInfo("Found voucher $code");
			return $this->vouchers[$code];
		}

		throw new VoucherNotFoundException("Voucher with code $code not found");
	}

	public function useVoucher( Voucher $voucher, string $bookingId ): void {
		$this->voucherApiMock?->useVoucher( $voucher, $bookingId );
		$this->logInfo("{$voucher->getCode()} used for booking $bookingId");
	}

	public function createVouchers(): void{
		$code = "TEST";

		for ($i = 1; $i <= 10; $i++) {
			$voucher = (new Voucher())
				->setCode($code . $i)
				->setType($i % 4 <= 2 ? VoucherType::Amount : VoucherType::Percentage)
				->setAmount($i)
				->setAvailable($i)
				->setCourseTemplate($i)
				->setForCourseTemplate($i % 4 <= 1)
				->setValidUntil(new DateTime("+$i days"));

			$this->vouchers[$code.$i] = $voucher;
		}
	}
}