<?php

namespace Tests\Feature;

use Tests\TestCase;

/**
 * .env.example is the only instruction an admin gets.
 *
 * It is not documentation, it is the file somebody copies and fills in, so a
 * key that is missing from it is a setting nobody knows to set, and a key
 * declared twice is worse: the later definition wins, so the obvious one gets
 * filled in and silently ignored.
 *
 * Found by testing rather than by reading: GOOGLE_ADS_DEVELOPER_TOKEN and
 * GOOGLE_ADS_LOGIN_CUSTOMER_ID were each declared twice, once for the campaign
 * API and once for the keyword planner, so filling in the campaign block did
 * nothing and Google Ads publishing would have failed with an empty developer
 * token and no clue why.
 */
class EnvExampleIsUsableTest extends TestCase
{
    /** @return list<string> */
    private function keys(): array
    {
        preg_match_all('/^([A-Z0-9_]+)=/m', (string) file_get_contents(base_path('.env.example')), $found);

        return $found[1];
    }

    /** A key declared twice is a key one of whose values is thrown away. */
    public function test_no_key_is_declared_twice(): void
    {
        $counts = array_count_values($this->keys());
        $duplicates = array_keys(array_filter($counts, fn (int $n): bool => $n > 1));

        $this->assertSame([], $duplicates, 'Declared more than once; the later definition silently wins.');
    }

    /**
     * Everything the Google integrations read has somewhere to be set.
     *
     * Both of them: the campaign API in config/services.php and the keyword
     * planner in config/google-ads.php. They are separate integrations with
     * separate OAuth clients that happen to share a developer token, which is
     * exactly why the duplicates arose.
     */
    public function test_every_google_setting_has_a_home(): void
    {
        $keys = $this->keys();

        foreach ([
            'GOOGLE_ADS_DEVELOPER_TOKEN',
            'GOOGLE_ADS_OAUTH_CLIENT_ID',
            'GOOGLE_ADS_OAUTH_CLIENT_SECRET',
            'GOOGLE_ADS_REFRESH_TOKEN',
            'GOOGLE_ADS_LOGIN_CUSTOMER_ID',
            'GOOGLE_ADS_CUSTOMER_ID',
            'GOOGLE_ADS_CLIENT_ID',
            'GOOGLE_ADS_CLIENT_SECRET',
        ] as $key) {
            $this->assertContains($key, $keys, "{$key} is read by config but cannot be set.");
        }
    }

    /**
     * A flag that changes who can read whose chats has to be discoverable.
     *
     * Undocumented, the only way to learn it exists is to read the source of
     * the thing it turns off.
     */
    public function test_the_chat_privacy_flag_is_documented(): void
    {
        $this->assertContains('ARB_SHARED_CONVERSATIONS', $this->keys());
    }
}
