<?php

namespace Tests\Feature;

use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\FeatureTestTrait;

/**
 * Campaign Management search has to find a campaign that is not among the
 * 1,000 most recently modified. The grid used to load that window first and
 * only then filter, so an older Hearst campaign came back as
 * "No matching records found" while the campaigns export still listed it.
 *
 * Run with:
 *   php8.2 -d newrelic.enabled=0 vendor/bin/phpunit -c phpunit.feature.xml tests/feature/CampaignGridSearchTest.php
 */
final class CampaignGridSearchTest extends CIUnitTestCase
{
    use FeatureTestTrait;

    public function testIdSearchFindsACampaignOutsideTheRecentWindow(): void
    {
        $db = \Config\Database::connect('default');

        // Own the campaigns directly. A linked sub-user's session resolves to
        // its master, and the grid then queries that other id.
        $advRow = $db->query(
            "SELECT c.advertiser_id AS adv_id, COUNT(*) AS n
             FROM campaign c
             JOIN Advertiser_info a ON a.adv_id = c.advertiser_id
             WHERE c.hidden = 0 AND c.status <> 'X'
               AND (a.masterid IS NULL OR a.masterid = 0 OR a.masterid = c.advertiser_id)
             GROUP BY c.advertiser_id
             HAVING n > 1000
             ORDER BY n DESC
             LIMIT 1"
        )->getRowArray();

        if ($advRow === null) {
            $this->markTestSkipped('No advertiser with more than 1,000 campaigns in this database');
        }

        $advId = (int) $advRow['adv_id'];
        $old = $db->query(
            "SELECT id, name FROM campaign
             WHERE advertiser_id = ? AND hidden = 0 AND status <> 'X'
             ORDER BY last_modified ASC
             LIMIT 1",
            [$advId]
        )->getRowArray();
        $this->assertNotEmpty($old, 'the account should have a campaign to search for');

        $id = (int) $old['id'];

        $body = $this->search($advId, (string) $id);
        $ids = array_map(static fn ($row) => (int) ($row['id'] ?? 0), $body['data'] ?? []);

        $this->assertContains($id, $ids);
        $this->assertGreaterThan(0, (int) ($body['recordsFiltered'] ?? 0));
    }

    public function testHearstPrefixSearchFindsThePausedCampaign(): void
    {
        $term = 'Search_2_AM_HTV_Professional_Solutions_The_Better_Payment_Processor_Month4_10';
        $db = \Config\Database::connect('default');
        $row = $db->query(
            'SELECT id FROM campaign WHERE advertiser_id = 13421 AND id = 125961 AND name LIKE ?',
            ['%' . $term . '%']
        )->getRowArray();
        if ($row === null) {
            $this->markTestSkipped('Hearst campaign 125961 is not in this database');
        }

        // The grid's default sort is Spent, a stats column, which is what the
        // search box sends. sort_by=name would hide a bug on that path.
        $result = $this->withSession([
            'logged_in' => 1,
            'adv_id'    => 13421,
            'user_id'   => 13421,
            'role'      => 'admin',
        ])->post('api/campaign/list', [
            'draw'     => 1,
            'start'    => 0,
            'length'   => 25,
            'sort_by'  => 'total_spent',
            'sort_dir' => 'desc',
            'search'   => ['value' => $term],
        ]);

        $result->assertStatus(200);
        $body = json_decode($result->getJSON(), true);
        $ids = array_map(static fn ($r) => (int) ($r['id'] ?? 0), $body['data'] ?? []);

        $this->assertContains(125961, $ids);
        $this->assertSame('Paused', $body['data'][array_search(125961, $ids, true)]['status'] ?? null);
    }

    public function testNameSearchFindsThatSameCampaign(): void
    {
        $db = \Config\Database::connect('default');
        $advRow = $db->query(
            "SELECT c.advertiser_id AS adv_id
             FROM campaign c
             JOIN Advertiser_info a ON a.adv_id = c.advertiser_id
             WHERE c.hidden = 0 AND c.status <> 'X'
               AND (a.masterid IS NULL OR a.masterid = 0 OR a.masterid = c.advertiser_id)
             GROUP BY c.advertiser_id
             HAVING COUNT(*) > 1000
             ORDER BY COUNT(*) DESC
             LIMIT 1"
        )->getRowArray();

        if ($advRow === null) {
            $this->markTestSkipped('No advertiser with more than 1,000 campaigns in this database');
        }

        $advId = (int) $advRow['adv_id'];
        $old = $db->query(
            "SELECT id, name FROM campaign
             WHERE advertiser_id = ? AND hidden = 0 AND status <> 'X'
               AND name <> ''
             ORDER BY last_modified ASC
             LIMIT 1",
            [$advId]
        )->getRowArray();

        $body = $this->search($advId, (string) $old['name']);
        $ids = array_map(static fn ($row) => (int) ($row['id'] ?? 0), $body['data'] ?? []);

        $this->assertContains((int) $old['id'], $ids);
    }

    /**
     * @return array<string,mixed>
     */
    private function search(int $advId, string $term): array
    {
        $result = $this->withSession([
            'logged_in' => 1,
            'adv_id'    => $advId,
            'user_id'   => $advId,
            'role'      => 'admin',
        ])->post('api/campaign/list', [
            'draw'     => 1,
            'start'    => 0,
            'length'   => 25,
            'sort_by'  => 'name',
            'sort_dir' => 'asc',
            'search'   => ['value' => $term],
        ]);

        $result->assertStatus(200);
        $body = json_decode($result->getJSON(), true);
        $this->assertIsArray($body);

        return $body;
    }
}
