<?php

namespace Tests\Feature;

use App\Models\Location;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

/**
 * Why two tests failed at random, roughly one run in twenty.
 *
 * locations.iso_code is a globally unique two-character country identity, and
 * LocationFactory's default row is a country. Overriding only the type leaves
 * the country's code behind, so `Location::factory()->create(['type' => 'city',
 * 'country_code' => 'US'])` produced a city named "France" holding iso_code FR
 * - and then collided with the seeded countries through that unique index.
 *
 * The factory picks from 249 codes and the seeder inserts 6, so each such row
 * had a 2.4% chance of landing on one, and faker's unique() does not help: it
 * keeps picks distinct within a run and knows nothing about rows a seeder
 * inserted directly. DuplicateAdSetTest and AddingAnAdSetToALiveCampaignTest
 * were the two doing it.
 *
 * This is the collision forced rather than waited for, because a flake that
 * fails one run in twenty cannot be shown fixed by a run that passes.
 */
class ACityDoesNotTakeACountrysIsoCodeTest extends TestCase
{
    use RefreshDatabase;
    use SeedsVerifiedCountries;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seedVerifiedCountries();
    }

    /** The shape the two tests used, with the code the faker would have picked. */
    public function test_a_city_carrying_a_seeded_countrys_code_is_refused(): void
    {
        $this->expectException(QueryException::class);

        Location::factory()->create([
            'type' => 'city',
            'country_code' => 'US',
            // What the factory leaves behind when only the type is overridden.
            // FR is seeded, so this is the one-in-twenty run.
            'iso_code' => 'FR',
            'source_key' => 'forced-collision',
        ]);
    }

    /** And the shape they use now. */
    public function test_a_city_with_no_iso_code_is_fine_however_many_exist(): void
    {
        $cities = collect(range(1, 10))->map(fn (int $i): Location => Location::factory()->create([
            'type' => 'city',
            'country_code' => 'US',
            'iso_code' => null,
            'source_key' => 'city-'.$i,
        ]));

        $this->assertCount(10, $cities);
        $this->assertCount(10, $cities->pluck('id')->unique());

        foreach ($cities as $city) {
            $this->assertNull($city->iso_code);
        }

        // The seeded countries are untouched, which is the point: a city has no
        // claim on a country's identity.
        $this->assertSame('FR', Location::query()->where('type', 'country')->where('iso_code', 'FR')->value('iso_code'));
    }

    /**
     * No test anywhere creates a non-country location that inherits a code.
     *
     * Named files were not enough: two were fixed and a third turned up in
     * CrossPlatformDmaTest, creating a DMA across three tests, because the
     * first search only matched calls written on a single line. So this looks
     * for the shape rather than for the files that happened to have it.
     */
    public function test_no_test_creates_a_non_country_location_without_nulling_the_code(): void
    {
        $offenders = [];

        foreach ($this->suiteFiles() as $path) {
            $source = (string) file_get_contents($path);
            $offset = 0;

            while (($at = strpos($source, 'Location::factory()', $offset)) !== false) {
                $offset = $at + 1;
                $statement = substr($source, $at, 600);
                $end = strpos($statement, ');');
                $statement = $end === false ? $statement : substr($statement, 0, $end + 2);

                if (preg_match("/'type'\s*=>\s*'(\w+)'/", $statement, $type) !== 1) {
                    continue;
                }

                if ($type[1] === 'country' || str_contains($statement, 'iso_code')) {
                    continue;
                }

                $offenders[] = sprintf(
                    '%s:%d creates a %s inheriting a country iso_code',
                    basename($path),
                    substr_count(substr($source, 0, $at), "\n") + 1,
                    $type[1],
                );
            }
        }

        $this->assertSame([], $offenders, implode("\n", $offenders));
    }

    /**
     * Every PHP file under tests/.
     *
     * Not named testFiles(): Pint's php_unit_method_casing fixer renames a
     * method whose name starts with "test" in a test class, which turned this
     * into test_files() and left the caller looking for a method that no longer
     * existed.
     *
     * @return list<string>
     */
    private function suiteFiles(): array
    {
        $files = [];
        $directory = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(base_path('tests')));

        foreach ($directory as $file) {
            if ($file->isFile() && $file->getExtension() === 'php') {
                $files[] = $file->getPathname();
            }
        }

        return $files;
    }
}
