<?php

namespace Tests\Feature;

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

/**
 * GET, PATCH and DELETE /v1/advertisers/{id} against throwaway advertisers,
 * which are removed with their api_keys, history and status log rows.
 *
 * 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/AdvertiserCrudTest.php
 */
final class AdvertiserCrudTest extends CIUnitTestCase
{
    use FeatureTestTrait;

    private const PREFIX = 'zzad2666';

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

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

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

    public function testShowReturnsTheAccountWithoutThePassword(): void
    {
        [$advId, $username] = $this->createAdvertiser();

        $response = $this->authed()->get('v1/advertisers/' . $advId);

        $response->assertStatus(200);
        $body = $this->json($response);
        $this->assertTrue($body['status']);
        $this->assertSame($advId, $body['adv_id']);
        $this->assertSame($username, $body['accountid']);
        $this->assertSame('Ada', $body['firstname']);
        $this->assertSame('EC1A', $body['zipcode']);
        $this->assertSame('5551112222', $body['phone']);
        $this->assertSame('PP', $body['account_type']);
        $this->assertSame(0, $body['status_code']);
        $this->assertGreaterThan(0, $body['creation']);
        $this->assertArrayNotHasKey('passclr', $body);
        $this->assertArrayNotHasKey('pass_clr', $body);
        $this->assertArrayNotHasKey('pass_hash', $body);
        $this->assertArrayNotHasKey('api_key', $body);
        $this->assertStringNotContainsString('secret1', (string) $response->response()->getBody());
    }

    public function testAnUnknownAdvertiserIsNotFound(): void
    {
        $max = (int) ($this->conn->table('Advertiser_info')->selectMax('adv_id')->get()->getRow()->adv_id ?? 0);

        foreach (['get', 'patch', 'delete'] as $method) {
            $response = $this->authed()->{$method}('v1/advertisers/' . ($max + 1000), ['firstname' => 'X']);
            $response->assertStatus(404);
            $body = $this->json($response);
            $this->assertFalse($body['status']);
            $this->assertSame(AdvertiserAccountService::NOT_FOUND_MESSAGE, $body['message']);
        }
    }

    public function testUpdateChangesOnlyTheSentFieldsAndWritesHistory(): void
    {
        [$advId] = $this->createAdvertiser();

        $response = $this->authed()->patch('v1/advertisers/' . $advId, [
            'firstname'  => 'Augusta',
            'zipcode'    => 'W1',
            'passclr'    => 'secret2',
            'updated_by' => 'mason.test',
        ]);

        $response->assertStatus(200);
        $body = $this->json($response);
        $this->assertSame('Augusta', $body['firstname']);
        $this->assertSame('W1', $body['zipcode']);
        $this->assertSame('Lovelace', $body['lastname']);

        $row = $this->conn->table('Advertiser_info')->where('adv_id', $advId)->get()->getRowArray();
        $this->assertSame('Augusta', $row['firstname']);
        $this->assertSame('W1', $row['zip']);
        $this->assertSame('secret2', $row['pass_clr']);
        $this->assertSame('Lovelace', $row['lastname']);
        $this->assertSame('London', $row['city']);

        $history = $this->conn->table('Advertiser_info_history')->where('adv_id', $advId)->get()->getResultArray();
        $this->assertCount(1, $history);
        $this->assertSame('mason.test', $history[0]['updated_by']);
        $this->assertSame(
            ['firstname' => 'Augusta', 'zip' => 'W1', 'pass_clr' => '(changed)'],
            unserialize($history[0]['new_values'])
        );
        $this->assertSame(
            ['firstname' => 'Ada', 'zip' => 'EC1A', 'pass_clr' => '(changed)'],
            unserialize($history[0]['old_values'])
        );
    }

    public function testUpdateWithNoChangeWritesNoHistory(): void
    {
        [$advId] = $this->createAdvertiser();

        $response = $this->authed()->put('v1/advertisers/' . $advId, ['firstname' => 'Ada', 'city' => 'London']);

        $response->assertStatus(200);
        $this->assertSame(0, $this->conn->table('Advertiser_info_history')->where('adv_id', $advId)->countAllResults());
    }

    public function testUpdateRejectsReadOnlyUnknownAndEmptyBodies(): void
    {
        [$advId, $username] = $this->createAdvertiser();

        $cases = [
            ['accountid' => 'renamed'],
            ['status' => 1],
            [],
            ['firstname' => ['nested']],
            ['account_type' => 'TOOLONG'],
        ];
        foreach ($cases as $input) {
            $response = $this->authed()->patch('v1/advertisers/' . $advId, $input);
            $response->assertStatus(400);
            $this->assertFalse($this->json($response)['status']);
        }

        $row = $this->conn->table('Advertiser_info')->where('adv_id', $advId)->get()->getRowArray();
        $this->assertSame($username, $row['Advertiser']);
        $this->assertSame('Ada', $row['firstname']);
        $this->assertSame('PP', $row['account_type']);
        $this->assertSame(0, $this->conn->table('Advertiser_info_history')->where('adv_id', $advId)->countAllResults());
    }

    public function testDeleteDeactivatesAndKeepsTheRowAndKey(): void
    {
        [$advId, $username] = $this->createAdvertiser();

        foreach ([1, 2] as $attempt) {
            $response = $this->authed()->delete('v1/advertisers/' . $advId);
            $response->assertStatus(200);
            $this->assertSame(
                ['status' => true, 'adv_id' => $advId, 'status_code' => 2],
                $this->json($response),
                'attempt ' . $attempt
            );
        }

        $row = $this->conn->table('Advertiser_info')->where('adv_id', $advId)->get()->getRowArray();
        $this->assertSame('2', (string) $row['status']);
        $this->assertSame(1, $this->conn->table('api_keys')->where('user_id', $advId)->countAllResults());

        if ($this->conn->tableExists('Advertiser_status_log')) {
            $logged = $this->conn->table('Advertiser_status_log')->where('advertiser', $username)->countAllResults();
            $this->assertSame(1, $logged);
        }
    }

    public function testEveryRouteRequiresBasicAuth(): void
    {
        [$advId] = $this->createAdvertiser();

        foreach (['get', 'patch', 'put', 'delete'] as $method) {
            $response = $this->withBodyFormat('json')->{$method}('v1/advertisers/' . $advId, ['firstname' => 'X']);
            $response->assertStatus(401);
        }

        $row = $this->conn->table('Advertiser_info')->where('adv_id', $advId)->get()->getRowArray();
        $this->assertSame('Ada', $row['firstname']);
        $this->assertSame('0', (string) $row['status']);
    }

    /**
     * @return array{0:int, 1:string}
     */
    private function createAdvertiser(): array
    {
        $username = self::PREFIX . bin2hex(random_bytes(4));
        $result   = (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, $result['code']);

        return [(int) $result['body']['adv_id'], $username];
    }

    private function authed()
    {
        $auth = 'Basic ' . base64_encode(ApiConstants::admediaApiUser() . ':' . ApiConstants::admediaApiPass());

        return $this->withBodyFormat('json')->withHeaders(['Authorization' => $auth]);
    }

    /**
     * @return array<string, mixed>
     */
    private function json($response): array
    {
        return json_decode((string) $response->response()->getBody(), true);
    }

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

        foreach ($rows as $row) {
            $advId = (int) $row['adv_id'];
            $this->conn->table('api_keys')->where('user_id', $advId)->delete();
            $this->conn->table('Advertiser_info_history')->where('adv_id', $advId)->delete();
            $this->conn->table('Advertiser_info')->where('adv_id', $advId)->delete();
        }

        if ($this->conn->tableExists('Advertiser_status_log')) {
            $this->conn->table('Advertiser_status_log')->like('advertiser', self::PREFIX, 'after')->delete();
        }
    }
}
