<?php

declare(strict_types=1);

use Cake\Datasource\ConnectionManager;
use Cake\TestSuite\TestCase;
use PHPUnit\Framework\MockObject\MockObject;

class StripePlanTest extends TestCase
{
    private StripePlan $Model;
    private MockObject $Source;

    public function setUp(): void
    {
        parent::setUp();
        $this->Model = new StripePlan();
        $this->Model->setDataSource('stripe_test');
        $sources = ConnectionManager::enumConnectionObjects();
        $this->skipIf(!array_key_exists('stripe_test', $sources), '`stripe_test` db config not found');
        $this->Source = $this->Model->getDataSource('stripe_test');
        $this->Source->Http = $this->createMock(HttpSocket::class);
    }

    public function tearDown(): void
    {
        parent::tearDown();
        unset($this->Model);
    }

    public function testValidation(): void
    {
        $this->Model->set(['StripePlan' => []]);
        $this->assertFalse($this->Model->validates());

        $this->assertArrayHasKey('id', $this->Model->validationErrors);
        $this->assertArrayHasKey('amount', $this->Model->validationErrors);
        $this->assertArrayHasKey('currency', $this->Model->validationErrors);
        $this->assertArrayHasKey('interval', $this->Model->validationErrors);
        $this->assertArrayHasKey('name', $this->Model->validationErrors);
        $this->assertArrayNotHasKey('trial_period_days', $this->Model->validationErrors);
    }

    public function testFlow(): void
    {
        $this->Source->Http->method('request')->willReturn(json_encode([
            'id' => 'Basic',
            'amount' => '500',
        ]));

        $results = $this->Model->save([
            'StripePlan' => [
                'id' => 'Basic',
                'amount' => 500,
                'currency' => 'usd',
                'interval' => 'month',
                'name' => 'Basic Plan'
            ]
        ]);

        $this->assertNotFalse($results);

        $id = $this->Model->id;
        $results = $this->Model->read();
        $this->assertEquals($id, $results['StripePlan']['id']);
        $this->assertEquals(500, $results['StripePlan']['amount']);
        $this->assertTrue($this->Model->delete($id));
    }
}