<?php

namespace Tests\Feature;

use App\Filters\InternalBasicAuth;
use App\Services\Advertiser\CreateAdvertiserService;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\FeatureTestTrait;
use Config\ApiConstants;

/**
 * Creates a throwaway advertiser through CreateAdvertiserService and the
 * POST /v1/advertisers route, then deletes the row and its api_keys row.
 *
 * 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/CreateAdvertiserTest.php
 */
final class CreateAdvertiserTest 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 testCreateWritesTheSameRowTheMngtPageInsertsAndIssuesAKey(): void
    {
        $username = self::PREFIX . bin2hex(random_bytes(4));
        $before   = time();

        $result = (new CreateAdvertiserService($this->conn))->create([
            'accountid'    => $username,
            'passclr'      => 'secret1',
            'firstname'    => 'Ada',
            'lastname'     => 'Lovelace',
            'company'      => 'Analytical Engines',
            'address1'     => '1 Note St',
            'address2'     => 'Suite 2',
            'city'         => 'London',
            'state'        => 'LN',
            'country'      => 'UK',
            'zipcode'      => 'EC1A',
            'phone'        => '5551112222',
            'fax'          => '5553334444',
            'website'      => 'https://example.test',
            'email'        => 'ada@example.test',
            'account_type' => 'IO',
            'status'       => '1',
        ]);

        $this->assertSame(201, $result['code']);
        $this->assertTrue($result['body']['status']);
        $advId = (int) $result['body']['adv_id'];
        $this->assertGreaterThan(0, $advId);
        $this->assertSame(1, preg_match('/^[0-9a-z]{40}$/', $result['body']['api_key']));

        $row = $this->conn->table('Advertiser_info')->where('adv_id', $advId)->get()->getRowArray();
        $this->assertSame($username, $row['Advertiser']);
        $this->assertSame('Ada', $row['firstname']);
        $this->assertSame('Lovelace', $row['lastname']);
        $this->assertSame('Analytical Engines', $row['company']);
        $this->assertSame('1 Note St', $row['address1']);
        $this->assertSame('Suite 2', $row['address2']);
        $this->assertSame('London', $row['city']);
        $this->assertSame('LN', $row['state']);
        $this->assertSame('UK', $row['country']);
        $this->assertSame('EC1A', $row['zip']);
        $this->assertSame('5551112222', $row['telephone']);
        $this->assertSame('5553334444', $row['fax']);
        $this->assertSame('secret1', $row['pass_clr']);
        $this->assertSame('', $row['pass_hash']);
        $this->assertSame('https://example.test', $row['website']);
        $this->assertSame('ada@example.test', $row['email']);
        $this->assertSame('AD', $row['admin_type']);
        $this->assertSame('0', (string) $row['rmx_id']);
        $this->assertSame('0', (string) $row['rmx_io']);
        $this->assertSame('IO', $row['account_type']);
        // The page inserts status as ''. The tinyint column stores that as 0,
        // and the posted status value is ignored.
        $this->assertSame('0', (string) $row['status']);
        $this->assertGreaterThanOrEqual($before, (int) $row['creation']);
        $this->assertLessThanOrEqual(time(), (int) $row['creation']);

        $key = $this->conn->table('api_keys')->where('user_id', $advId)->get()->getRowArray();
        $this->assertSame($result['body']['api_key'], $key['key']);
        $this->assertSame('2', (string) $key['level']);
        $this->assertSame('1', (string) $key['ignore_limits']);
        $this->assertSame(40, strlen($key['key']));
    }

    public function testADuplicateUsernameReturnsThePageError(): void
    {
        $username = self::PREFIX . bin2hex(random_bytes(4));
        $input    = $this->input($username);
        $service  = new CreateAdvertiserService($this->conn);

        $first = $service->create($input);
        $this->assertSame(201, $first['code']);

        $second = $service->create($input);
        $this->assertSame(409, $second['code']);
        $this->assertFalse($second['body']['status']);
        $this->assertSame(CreateAdvertiserService::DUPLICATE_MESSAGE, $second['body']['message']);

        $count = $this->conn->table('Advertiser_info')->where('Advertiser', $username)->countAllResults();
        $this->assertSame(1, $count);
    }

    public function testMissingBasicAuthIsRejected(): void
    {
        $request = service('request');
        $request->setMethod('POST');
        $request->removeHeader('Authorization');

        $result = (new InternalBasicAuth())->before($request);

        $this->assertInstanceOf(ResponseInterface::class, $result);
        $this->assertSame(401, $result->getStatusCode());
        $body = json_decode((string) $result->getBody(), true);
        $this->assertFalse($body['status']);
        $this->assertSame('Unauthorized', $body['message']);
    }

    public function testTheRouteRejectsAMissingPasswordAndCreatesWithTheInternalUser(): void
    {
        $username = self::PREFIX . bin2hex(random_bytes(4));

        $denied = $this->withBodyFormat('json')->post('v1/advertisers', $this->input($username));
        $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('v1/advertisers', $this->input($username));

        $ok->assertStatus(201);
        $body = json_decode((string) $ok->response()->getBody(), true);
        $this->assertTrue($body['status']);
        $this->assertSame(1, preg_match('/^[0-9a-z]{40}$/', $body['api_key']));

        $row = $this->conn->table('Advertiser_info')
            ->where('adv_id', (int) $body['adv_id'])
            ->get()
            ->getRowArray();
        $this->assertSame($username, $row['Advertiser']);
        $this->assertSame('', $row['pass_hash']);
    }

    /**
     * @return array<string, string>
     */
    private function input(string $username): array
    {
        return [
            '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',
        ];
    }

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

        foreach ($rows as $row) {
            $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();
        }
    }
}
