<?php
declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Validation\Validator;

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

		$this->setTable('stripe_charges');
		$this->setPrimaryKey('id');
		$this->setDisplayField('id');

		$this->addBehavior('Timestamp');
	}

	public function validationDefault(Validator $validator): Validator
	{
		$validator
			->integer('amount')
			->requirePresence('amount', 'create')
			->notEmptyString('amount');

		$validator
			->scalar('currency')
			->maxLength('currency', 3)
			->requirePresence('currency', 'create')
			->notEmptyString('currency');

		$validator
			->scalar('customer')
			->maxLength('customer', 255)
			->allowEmptyString('customer');

		return $validator;
	}

	public function createCharge(array $data): bool
	{
		$charge = $this->newEntity([
			'amount' => 500,
			'currency' => 'usd',
			'customer' => $data['customer'] ?? null
		]);

		return (bool) $this->save($charge);
	}

	public function isChargeSuccessfullyHappened(int|string $chargeId): array
	{
		return $this->find()
			->where(['id' => $chargeId])
			->all()
			->toArray();
	}
}
