<?php

namespace Tests\Feature;

use App\Services\Advertiser\AdvertiserBudgetApiService;
use App\Services\Advertiser\CreateAdvertiserService;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\FeatureTestTrait;
use Config\ApiConstants;

/**
 * Credits, adjustments and budget reads against a throwaway advertiser.
 *
 * Run with the feature bootstrap:
 *   php8.2 -d newrelic.enabled=0 -d newrelic.daemon.dont_launch=3 \
 *     vendor/bin/phpunit --bootstrap tests/feature_bootstrap.php \
 *     tests/feature/AdvertiserBudgetApiTest.php
 */
final class AdvertiserBudgetApiTest extends CIUnitTestCase
{
    use FeatureTestTrait;

    private const PREFIX = 'zzbapi';

    /** @var \CodeIgniter\Database\BaseConnection */
    private $conn;

    /** @var AdvertiserBudgetApiService */
    private $budget;

    protected function setUp(): void
    {
        parent::setUp();
        $this->conn = \Config\Database::connect('default');
        $this->budget = new AdvertiserBudgetApiService($this->conn);
        $this->cleanup();
    }

    protected function tearDown(): void
    {
        $this->cleanup();
        parent::tearDown();
    }

    public function testCreditInsertsAZeroBudgetAndATermsExtendedRow(): void
    {
        $advertiser = $this->advertiser();

        $first = $this->budget->credit($advertiser['adv_id'], $this->credit('10.00', 'Payment', 'line 1'), '127.0.0.1');
        $this->assertSame(200, $first['code']);
        $this->assertTrue($first['body']['status']);
        $this->assertSame('10.00', $first['body']['amount']);
        $this->assertSame('10.00', $first['body']['applied_amount']);
        $this->assertSame('0.00', $first['body']['budget']);
        $this->assertFalse($first['body']['clamped']);
        $this->assertSame('credit', $first['body']['direction']);
        $this->assertSame('Terms extended', $first['body']['type']);
        $this->assertSame('line 1', $first['body']['comment']);

        $row = $this->conn->table('Advertiser_budget')
            ->where('advertiser', $advertiser['name'])
            ->get()
            ->getRowArray();
        $this->assertSame('0.00000000', $row['budget']);

        $ledger = $this->conn->table('Advertiser_billing')
            ->where('advertiser', $advertiser['name'])
            ->where('comment', 'line 1')
            ->get()
            ->getRowArray();
        $this->assertSame('10.00', $ledger['billing_amount']);
        $this->assertSame('line 1', $ledger['comment']);
        $this->assertSame('Terms extended', $ledger['type']);
        $this->assertSame('api', $ledger['user']);
    }

    public function testASecondCreditInsertsAnotherRowAndLeavesTheBudget(): void
    {
        $advertiser = $this->advertiser();
        $input = $this->credit('25.00');

        $first = $this->budget->credit($advertiser['adv_id'], $input, '127.0.0.1');
        $second = $this->budget->credit($advertiser['adv_id'], $input, '127.0.0.1');

        $this->assertSame(200, $first['code']);
        $this->assertSame(200, $second['code']);
        $this->assertSame('0.00', $first['body']['budget']);
        $this->assertSame('0.00', $second['body']['budget']);
        $this->assertSame('25.00', $second['body']['applied_amount']);
        $this->assertSame(
            2,
            $this->conn->table('Advertiser_billing')->where('advertiser', $advertiser['name'])->countAllResults()
        );
        $this->assertSame('0.00000000', $this->storedBudget($advertiser['name']));
    }

    public function testDebitClampsAtZero(): void
    {
        $advertiser = $this->advertiser();
        $this->storeBudget($advertiser['name'], '5.00000000');

        $debit = $this->budget->adjust(
            $advertiser['adv_id'],
            $this->adjustment('20.00', 'debit'),
            '127.0.0.1'
        );

        $this->assertSame(200, $debit['code']);
        $this->assertSame('20.00', $debit['body']['amount']);
        $this->assertSame('5.00', $debit['body']['applied_amount']);
        $this->assertSame('0.00', $debit['body']['budget']);
        $this->assertTrue($debit['body']['clamped']);
        $this->assertSame('debit', $debit['body']['direction']);
        $this->assertSame(
            0,
            $this->conn->table('Advertiser_billing')->where('advertiser', $advertiser['name'])->countAllResults()
        );
    }

    public function testAdjustmentCreditAddsTheOverspend(): void
    {
        $advertiser = $this->advertiser();
        $this->storeBudget($advertiser['name'], '4.00000000');

        $topUp = $this->budget->adjust(
            $advertiser['adv_id'],
            $this->adjustment('1.25', 'credit'),
            '127.0.0.1'
        );

        $this->assertSame(200, $topUp['code']);
        $this->assertSame('5.25', $topUp['body']['budget']);
        $this->assertSame('1.25', $topUp['body']['applied_amount']);
        $this->assertFalse($topUp['body']['clamped']);
        $this->assertSame(
            0,
            $this->conn->table('Advertiser_billing')->where('advertiser', $advertiser['name'])->countAllResults()
        );
    }

    public function testPartialDebitLeavesTheRest(): void
    {
        $advertiser = $this->advertiser();
        $this->storeBudget($advertiser['name'], '10.00000000');

        $debit = $this->budget->adjust(
            $advertiser['adv_id'],
            $this->adjustment('4.00', 'debit'),
            '127.0.0.1'
        );

        $this->assertSame(200, $debit['code']);
        $this->assertSame('4.00', $debit['body']['applied_amount']);
        $this->assertSame('6.00', $debit['body']['budget']);
        $this->assertFalse($debit['body']['clamped']);
    }

    public function testAdjustmentCreditAtTheCeilingIsRejected(): void
    {
        $advertiser = $this->advertiser();
        $this->storeBudget($advertiser['name'], '9999999.99999999');

        $result = $this->budget->adjust(
            $advertiser['adv_id'],
            $this->adjustment('0.01', 'credit'),
            '127.0.0.1'
        );

        $this->assertSame(400, $result['code']);
        $this->assertSame('amount would exceed the budget maximum', $result['body']['message']);
        $this->assertSame('9999999.99999999', $this->storedBudget($advertiser['name']));
    }

    public function testCreditExtensionCannotReplaceAnExistingPrepaidBalance(): void
    {
        $advertiser = $this->advertiser();
        $this->storeBudget($advertiser['name'], '50.00000000');

        $result = $this->budget->credit($advertiser['adv_id'], $this->credit('1.00'), '127.0.0.1');

        $this->assertSame(400, $result['code']);
        $this->assertSame(AdvertiserBudgetApiService::MIXED_EXTENSION, $result['body']['message']);
        $this->assertSame('50.00000000', $this->storedBudget($advertiser['name']));
        $this->assertSame(
            0,
            $this->conn->table('Advertiser_billing')->where('advertiser', $advertiser['name'])->countAllResults()
        );
    }

    public function testUnknownAdvertiserIsNotFound(): void
    {
        $missing = $this->budget->credit(0, $this->credit('1.00'), '127.0.0.1');
        $this->assertSame(404, $missing['code']);
        $this->assertSame('Advertiser not found', $missing['body']['message']);

        $budget = $this->budget->showBudget(0);
        $this->assertSame(404, $budget['code']);
    }

    public function testTheRoutesRejectMissingBasicAuthAndApplyACredit(): void
    {
        $advertiser = $this->advertiser();
        $path = 'v1/advertisers/' . $advertiser['adv_id'] . '/billing/credits';

        $denied = $this->withBodyFormat('json')->post($path, $this->credit('2.00'));
        $denied->assertStatus(401);
        $deniedBody = json_decode((string) $denied->response()->getBody(), true);
        $this->assertFalse($deniedBody['status']);
        $this->assertSame('Unauthorized', $deniedBody['message']);

        $auth = 'Basic ' . base64_encode(ApiConstants::admediaApiUser() . ':' . ApiConstants::admediaApiPass());
        $ok = $this->withBodyFormat('json')
            ->withHeaders(['Authorization' => $auth])
            ->post($path, $this->credit('2.00'));
        $ok->assertStatus(200);
        $body = json_decode((string) $ok->response()->getBody(), true);
        $this->assertTrue($body['status']);
        $this->assertSame('0.00', $body['budget']);
        $this->assertSame('Terms extended', $body['type']);

        $budget = $this->withHeaders(['Authorization' => $auth])
            ->get('v1/advertisers/' . $advertiser['adv_id'] . '/budget');
        $budget->assertStatus(200);

        $this->storeBudget($advertiser['name'], '2.00000000');
        $adjust = $this->withBodyFormat('json')
            ->withHeaders(['Authorization' => $auth])
            ->post(
                'v1/advertisers/' . $advertiser['adv_id'] . '/billing/adjustments',
                $this->adjustment('0.50', 'debit')
            );
        $adjust->assertStatus(200);
        $adjustBody = json_decode((string) $adjust->response()->getBody(), true);
        $this->assertSame('1.50', $adjustBody['budget']);
        $this->assertFalse($adjustBody['clamped']);
        $this->assertSame(
            1,
            $this->conn->table('Advertiser_billing')->where('advertiser', $advertiser['name'])->countAllResults()
        );

        $unauthBudget = $this->withHeaders([])->get('v1/advertisers/' . $advertiser['adv_id'] . '/budget');
        $unauthBudget->assertStatus(401);
    }

    /**
     * @return array{adv_id:int,name:string}
     */
    private function advertiser(): array
    {
        $username = self::PREFIX . bin2hex(random_bytes(4));
        $created = (new CreateAdvertiserService($this->conn))->create([
            'accountid'    => $username,
            'passclr'      => 'secret1',
            'firstname'    => 'Ada',
            'lastname'     => 'Lovelace',
            'company'      => 'Analytical Engines',
            'address1'     => '1 Note St',
            'address2'     => '',
            'city'         => 'London',
            'state'        => 'LN',
            'country'      => 'UK',
            'zipcode'      => 'EC1A',
            'phone'        => '5551112222',
            'fax'          => '',
            'website'      => 'https://example.test',
            'email'        => 'ada@example.test',
            'account_type' => 'PP',
        ]);
        $this->assertSame(201, $created['code']);

        return [
            'adv_id' => (int) $created['body']['adv_id'],
            'name'   => $username,
        ];
    }

    /**
     * @return array<string, string>
     */
    private function credit(string $amount, string $type = '', string $comment = ''): array
    {
        $body = [
            'amount'  => $amount,
            'comment' => $comment,
        ];
        if ($type !== '') {
            $body['type'] = $type;
        }

        return $body;
    }

    /**
     * @return array<string, string>
     */
    private function adjustment(string $amount, string $direction): array
    {
        return [
            'amount'    => $amount,
            'direction' => $direction,
        ];
    }

    private function storeBudget(string $name, string $amount): void
    {
        $exists = $this->conn->table('Advertiser_budget')->where('advertiser', $name)->countAllResults();
        $row = [
            'budget'      => $amount,
            'last_update' => date('Y-m-d H:i:s'),
        ];
        if ($exists > 0) {
            $this->conn->table('Advertiser_budget')->where('advertiser', $name)->update($row);

            return;
        }

        $row['advertiser'] = $name;
        $this->conn->table('Advertiser_budget')->insert($row);
    }

    private function storedBudget(string $name): string
    {
        return (string) $this->conn->table('Advertiser_budget')
            ->where('advertiser', $name)
            ->get()
            ->getRowArray()['budget'];
    }

    private function cleanup(): void
    {
        $rows = $this->conn->table('Advertiser_info')
            ->select('adv_id, Advertiser')
            ->like('Advertiser', self::PREFIX, 'after')
            ->get()
            ->getResultArray();

        foreach ($rows as $row) {
            $this->conn->table('Advertiser_billing')->where('advertiser', $row['Advertiser'])->delete();
            $this->conn->table('Advertiser_budget')->where('advertiser', $row['Advertiser'])->delete();
            $this->conn->table('api_keys')->where('user_id', (int) $row['adv_id'])->delete();
            $this->conn->table('Advertiser_info')->where('adv_id', (int) $row['adv_id'])->delete();
        }
    }
}
