<?php

namespace Tests\Feature;

use App\Campaigns\Manager\CampaignSynchronizer;
use App\Campaigns\Manager\Editing\EditCapabilities;
use App\Campaigns\Manager\Editing\EntityEditor;
use App\Livewire\CampaignManager\EditEntity;
use App\Models\Campaign;
use App\Models\CampaignEntityEdit;
use App\Models\CampaignPlatformEntity;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Validation\ValidationException;
use Livewire\Livewire;
use Tests\TestCase;

/**
 * The plain parts of a Meta ad set's targeting: countries, age range, gender
 * and placements, merged into the targeting Meta holds so the rest survives.
 */
class CampaignManagerTargetingEditTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

    /** @var array{campaign: array<string, mixed>, adsets: list<array<string, mixed>>} */
    private array $meta = ['campaign' => [], 'adsets' => []];

    /** @var list<array{id: string, fields: array<string, mixed>}> */
    private array $writes = [];

    private bool $rejectScheduleCreation = false;

    protected function setUp(): void
    {
        parent::setUp();

        config([
            'platforms.meta.token' => 'test-token',
            'platforms.meta.mcp.enabled' => false,
            'platforms.guardrails.allowed_ad_accounts' => ['meta:*'],
            'platforms.guardrails.paused' => false,
            'platforms.guardrails.change_cooldown_seconds' => 0,
            'platforms.guardrails.max_changes_per_day' => 50,
            'campaign-manager.edit_platforms' => ['meta'],
            'campaign-manager.edit_categories' => ['name', 'targeting'],
        ]);

        $this->user = User::factory()->create();

        $this->meta['campaign'] = [
            'id' => '120252047635070626', 'name' => 'Winter Sale', 'status' => 'ACTIVE', 'effective_status' => 'ACTIVE',
            'objective' => 'OUTCOME_TRAFFIC', 'account_id' => '111',
        ];
        $this->meta['adsets'] = [[
            'id' => '2001', 'name' => 'US mobile', 'status' => 'ACTIVE', 'daily_budget' => '2500',
            'optimization_goal' => 'LINK_CLICKS', 'bid_strategy' => 'LOWEST_COST_WITHOUT_CAP',
            'targeting' => [
                'age_min' => 25,
                'age_max' => 54,
                'geo_locations' => ['countries' => ['US'], 'location_types' => ['home', 'recent']],
                'flexible_spec' => [['interests' => [['id' => '6003096812932', 'name' => 'Data analysis']]]],
                'publisher_platforms' => ['facebook'],
                'facebook_positions' => ['feed', 'story'],
                'device_platforms' => ['mobile'],
                'targeting_automation' => ['advantage_audience' => 0],
            ],
        ]];

        Http::fake(function (Request $request) {
            $path = (string) parse_url($request->url(), PHP_URL_PATH);

            if ($request->method() === 'DELETE' && basename($path) === '7001') {
                $this->meta['adsets'][0]['budget_schedules'] = ['data' => []];
                $this->meta['adsets'][0]['is_budget_schedule_enabled'] = false;

                return Http::response(['success' => true]);
            }

            if ($request->method() === 'POST') {
                $id = basename($path);
                $fields = array_diff_key($request->data(), ['access_token' => true]);
                $this->writes[] = ['id' => $id, 'fields' => $fields];

                if ($id === 'budget_schedules') {
                    if ($this->rejectScheduleCreation) {
                        return Http::response(['error' => ['message' => 'Budget boost creation refused', 'code' => 100]], 400);
                    }
                    $this->meta['adsets'][0]['budget_schedules'] = ['data' => [['id' => '7001', ...$fields]]];
                    $this->meta['adsets'][0]['is_budget_schedule_enabled'] = true;

                    return Http::response(['id' => '7001']);
                }
                $this->assertNotSame('7001', $id, 'Meta retired in-place schedule updates.');

                $stored = array_map(fn (mixed $value): mixed => is_string($value) && (str_starts_with($value, '{') || str_starts_with($value, '[')) ? json_decode($value, true) : $value, $fields);

                foreach ($this->meta['adsets'] as $i => $row) {
                    if ($row['id'] === $id) {
                        $this->meta['adsets'][$i] = [...$row, ...$stored];
                    }
                }

                return Http::response(['success' => true]);
            }

            return match (true) {
                str_ends_with($path, '/adsets') => Http::response(['data' => $this->meta['adsets']]),
                str_ends_with($path, '/ads') => Http::response(['data' => []]),
                default => Http::response($this->meta['campaign']),
            };
        });
    }

    private function campaign(): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'published',
            'ad_account_id' => 'act_111',
            'currency' => 'USD',
            'external_campaign_id' => '120252047635070626',
        ]);

        app(CampaignSynchronizer::class)->sync($campaign);

        return $campaign;
    }

    private function adSet(Campaign $campaign): CampaignPlatformEntity
    {
        return $campaign->platformEntities()->where('external_id', '2001')->sole();
    }

    private function editor(): EntityEditor
    {
        return app(EntityEditor::class);
    }

    private function capabilities(): EditCapabilities
    {
        return app(EditCapabilities::class);
    }

    /** @return array<string, mixed> */
    private function sentTargeting(int $write = 0): array
    {
        return json_decode((string) $this->writes[$write]['fields']['targeting'], true);
    }

    /** @param  array<string, mixed>  $values */
    private function assertRejected(Campaign $campaign, CampaignPlatformEntity $entity, array $values, string $field, string $message): void
    {
        try {
            $this->editor()->propose($campaign, $entity, $this->user, $values);
            $this->fail('Accepted '.json_encode($values));
        } catch (ValidationException $exception) {
            $this->assertStringContainsString($message, $exception->errors()[$field][0] ?? '');
        }
    }

    public function test_countries_ages_and_gender_are_merged_into_the_targeting_meta_holds(): void
    {
        $campaign = $this->campaign();
        $adSet = $this->adSet($campaign);

        $this->assertSame(['US'], EditCapabilities::current($adSet, 'countries'));
        $this->assertSame('all', EditCapabilities::current($adSet, 'genders'));

        $edit = $this->editor()->propose($campaign, $adSet, $this->user, [
            'countries' => 'ca, us,GB', 'age_min' => '30', 'age_max' => '65', 'genders' => 'women',
        ]);

        $this->assertSame(['CA', 'GB', 'US'], $edit->changes['countries']['after']);
        $this->assertSame('65+', EditCapabilities::display($adSet, 'age_max', 65));
        $this->assertStringContainsString('back into learning', implode(' ', $this->capabilities()->confirmations($adSet, $edit->changes)));

        $edit = $this->editor()->apply($edit, $this->user, acknowledged: true);

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame(['targeting'], array_keys($this->writes[0]['fields']));

        $sent = $this->sentTargeting();
        $this->assertSame(['CA', 'GB', 'US'], $sent['geo_locations']['countries']);
        $this->assertSame(['home', 'recent'], $sent['geo_locations']['location_types']);
        $this->assertSame([30, 65], [$sent['age_min'], $sent['age_max']]);
        $this->assertSame([2], $sent['genders']);
        $this->assertSame('6003096812932', $sent['flexible_spec'][0]['interests'][0]['id']);
        $this->assertSame('women', EditCapabilities::current($adSet->refresh(), 'genders'));

        $this->editor()->apply($this->editor()->propose($campaign, $adSet, $this->user, ['genders' => 'all']), $this->user, acknowledged: true);
        $this->assertArrayNotHasKey('genders', $this->sentTargeting(1));
    }

    public function test_dropping_a_placement_platform_drops_its_positions_and_none_means_automatic(): void
    {
        $campaign = $this->campaign();
        $adSet = $this->adSet($campaign);

        $edit = $this->editor()->propose($campaign, $adSet, $this->user, ['publisher_platforms' => ['instagram']]);
        $this->assertStringContainsString('Instagram account linked to the Page', implode(' ', $this->capabilities()->confirmations($adSet, $edit->changes)));
        $this->editor()->apply($edit, $this->user, acknowledged: true);

        $sent = $this->sentTargeting();
        $this->assertSame(['instagram'], $sent['publisher_platforms']);
        $this->assertArrayNotHasKey('facebook_positions', $sent);
        $this->assertSame(['mobile'], $sent['device_platforms']);

        $edit = $this->editor()->propose($campaign, $adSet->refresh(), $this->user, ['publisher_platforms' => []]);
        $this->assertSame('Automatic (Advantage+ placements)', EditCapabilities::display($adSet, 'publisher_platforms', $edit->changes['publisher_platforms']['after']));
        $this->assertSame(CampaignEntityEdit::Applied, $this->editor()->apply($edit, $this->user, acknowledged: true)->state);
        $this->assertArrayNotHasKey('publisher_platforms', $this->sentTargeting(1));
    }

    public function test_bad_targeting_is_refused_before_anything_is_sent(): void
    {
        $campaign = $this->campaign();
        $adSet = $this->adSet($campaign);

        $this->assertRejected($campaign, $adSet, ['countries' => 'USA'], 'countries', 'USA is not a two-letter country code');
        $this->assertRejected($campaign, $adSet, ['countries' => ' , '], 'countries', 'at least one country');
        $this->assertRejected($campaign, $adSet, ['age_min' => '60'], 'age_min', 'at or below the oldest');
        $this->assertRejected($campaign, $adSet, ['age_max' => '70'], 'age_max', 'between 18 and 65');
        $this->assertRejected($campaign, $adSet, ['publisher_platforms' => ['messenger']], 'publisher_platforms', 'only run alongside Facebook');
        $this->assertRejected($campaign, $adSet, ['publisher_platforms' => ['tiktok']], 'publisher_platforms', 'tiktok is not a placement');
        $this->assertSame([], $this->writes);
    }

    public function test_regions_and_advantage_audience_keep_their_parts_in_ads_manager(): void
    {
        $this->meta['adsets'][0]['targeting']['geo_locations']['regions'] = [['key' => '3847']];
        $this->meta['adsets'][0]['targeting']['targeting_automation']['advantage_audience'] = 1;
        $adSet = $this->adSet($this->campaign());

        $fields = $this->capabilities()->editableFields($adSet);
        $this->assertContains('publisher_platforms', $fields);
        $this->assertNotContains('countries', $fields);
        $this->assertNotContains('age_min', $fields);
        $this->assertNotContains('genders', $fields);

        $locked = $this->capabilities()->lockedFields($adSet);
        $this->assertStringContainsString('regions, cities or places', $locked['countries']);
        $this->assertStringContainsString('Advantage+ audience is on', $locked['genders']);
        $this->assertStringContainsString('Meta removed detailed-targeting exclusions', $locked['exclusions']);
        $this->assertArrayNotHasKey('targeting', $locked);
    }

    public function test_the_wizard_edits_countries_as_a_line_and_placements_as_ticks(): void
    {
        $campaign = $this->campaign();
        $adSet = $this->adSet($campaign);

        Livewire::actingAs($this->user)
            ->test(EditEntity::class, ['campaign' => $campaign, 'entity' => $adSet])
            ->assertSet('values.countries', 'US')
            ->assertSet('values.publisher_platforms', ['facebook'])
            ->assertSee('Audience Network')
            ->set('values.countries', 'US, CA')
            ->set('values.publisher_platforms', ['facebook', 'instagram'])
            ->call('review')
            ->assertHasNoErrors()
            ->assertSet('problem', null)
            ->assertSee('CA, US')
            ->assertSee('Facebook, Instagram')
            ->set('acknowledged', true)
            ->call('confirm')
            ->assertSee('Done.');

        $sent = $this->sentTargeting();
        $this->assertSame(['CA', 'US'], $sent['geo_locations']['countries']);
        $this->assertSame(['feed', 'story'], $sent['facebook_positions']);
    }

    public function test_advanced_audience_and_device_fields_preserve_unedited_targeting(): void
    {
        $campaign = $this->campaign();
        $entity = $this->adSet($campaign);
        $edit = $this->editor()->propose($campaign, $entity, $this->user, [
            'custom_audiences' => '[{"id":"1234"}]',
            'excluded_custom_audiences' => [['id' => '5678']],
            'excluded_geo_locations' => ['countries' => ['CA']],
            'locales' => [6, 24],
            'flexible_spec' => [['behaviors' => [['id' => '6001234567']]]],
            'device_platforms' => ['mobile', 'desktop'],
            'user_os' => ['iOS'],
            'user_device' => ['iPhone'],
            'excluded_user_device' => ['iPad'],
            'wireless_carrier' => ['Wifi'],
            'facebook_positions' => ['feed'],
            'targeting_relaxation_types' => ['custom_audience' => 0, 'lookalike' => 1],
            'advantage_audience' => 1,
        ]);
        $edit = $this->editor()->apply($edit, $this->user, acknowledged: true);

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $sent = $this->sentTargeting();
        $this->assertSame(['US'], $sent['geo_locations']['countries']);
        $this->assertSame(25, $sent['age_min']);
        $this->assertSame('1234', $sent['custom_audiences'][0]['id']);
        $this->assertSame('5678', $sent['excluded_custom_audiences'][0]['id']);
        $this->assertSame(['CA'], $sent['excluded_geo_locations']['countries']);
        $this->assertSame(['feed'], $sent['facebook_positions']);
        $this->assertSame(1, $sent['targeting_automation']['advantage_audience']);
        $this->assertSame(['Wifi'], $sent['wireless_carrier']);
    }

    public function test_geography_supports_cities_and_radius_and_can_remove_only_exclusions(): void
    {
        $campaign = $this->campaign();
        $entity = $this->adSet($campaign);
        $edit = $this->editor()->propose($campaign, $entity, $this->user, [
            'geo_locations' => ['cities' => [['key' => '2421836', 'radius' => 10, 'distance_unit' => 'mile']]],
            'excluded_geo_locations' => ['countries' => ['CA']],
        ]);
        $this->assertSame(CampaignEntityEdit::Applied, $this->editor()->apply($edit, $this->user, acknowledged: true)->state);
        $edit = $this->editor()->propose($campaign, $entity->refresh(), $this->user, ['excluded_geo_locations' => '{}']);
        $this->assertSame(CampaignEntityEdit::Applied, $this->editor()->apply($edit, $this->user, acknowledged: true)->state);
        $this->assertSame('2421836', $this->sentTargeting(1)['geo_locations']['cities'][0]['key']);
        $this->assertArrayNotHasKey('excluded_geo_locations', $this->sentTargeting(1));
    }

    public function test_malformed_nested_and_unallowlisted_audience_values_never_reach_meta(): void
    {
        $campaign = $this->campaign();
        $entity = $this->adSet($campaign);
        foreach ([
            ['flexible_spec', '{"bad":'],
            ['flexible_spec', [['account_id' => '123']]],
            ['custom_audiences', [['id' => '../123']]],
            ['geo_locations', ['custom_locations' => [['latitude' => 200, 'longitude' => 0, 'radius' => 10, 'distance_unit' => 'mile']]]],
            ['locales', ['invalid']],
            ['device_platforms', ['server']],
            ['instagram_positions', ['stream']],
        ] as [$field, $value]) {
            try {
                $this->editor()->propose($campaign, $entity, $this->user, [$field => $value]);
                $this->fail('Accepted invalid '.$field);
            } catch (ValidationException $exception) {
                $this->assertArrayHasKey($field, $exception->errors());
            }
        }
        $this->assertSame([], $this->writes);
    }

    public function test_advanced_audiences_are_stale_if_someone_changes_them_in_meta(): void
    {
        $campaign = $this->campaign();
        $edit = $this->editor()->propose($campaign, $this->adSet($campaign), $this->user, ['custom_audiences' => [['id' => '1234']]]);
        $this->meta['adsets'][0]['targeting']['custom_audiences'] = [['id' => '9999']];
        $edit = $this->editor()->apply($edit, $this->user, acknowledged: true);
        $this->assertSame(CampaignEntityEdit::Stale, $edit->state);
        $this->assertSame([], $this->writes);
    }

    public function test_the_wizard_accepts_structured_audiences_and_does_not_submit_unchanged_advanced_fields(): void
    {
        $campaign = $this->campaign();
        Livewire::actingAs($this->user)
            ->test(EditEntity::class, ['campaign' => $campaign, 'entity' => $this->adSet($campaign)])
            ->assertSee('Included locations (advanced)')
            ->set('values.custom_audiences', '[{"id":"1234"}]')
            ->call('review')
            ->assertHasNoErrors()
            ->assertSet('problem', null)
            ->set('acknowledged', true)
            ->call('confirm')
            ->assertSee('Done.');
        $this->assertSame('1234', $this->sentTargeting()['custom_audiences'][0]['id']);
        $this->assertSame(['US'], $this->sentTargeting()['geo_locations']['countries']);
    }

    public function test_roas_pacing_and_dayparting_writes_use_their_native_shapes(): void
    {
        config(['campaign-manager.edit_categories' => ['bid_strategy', 'schedule', 'optimization']]);
        $this->meta['adsets'][0] = [
            ...$this->meta['adsets'][0],
            'daily_budget' => null, 'lifetime_budget' => '25000', 'optimization_goal' => 'VALUE',
            'promoted_object' => ['pixel_id' => '123', 'custom_event_type' => 'PURCHASE'],
            'pacing_type' => ['standard'],
        ];
        $campaign = $this->campaign();
        $entity = $this->adSet($campaign);
        $edit = $this->editor()->propose($campaign, $entity, $this->user, [
            'bid_strategy' => 'LOWEST_COST_WITH_MIN_ROAS', 'roas_floor' => 2.5,
            'adset_schedule' => [['days' => [1, 2], 'start_minute' => 540, 'end_minute' => 1020, 'timezone_type' => 'ADVERTISER']],
        ]);
        $edit = $this->editor()->apply($edit, $this->user, acknowledged: true);
        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $fields = $this->writes[0]['fields'];
        $this->assertSame(25000, json_decode($fields['bid_constraints'], true)['roas_average_floor']);
        $this->assertArrayNotHasKey('promoted_object', $fields);
        $this->assertContains('day_parting', json_decode($fields['pacing_type'], true));
        $this->assertArrayNotHasKey('roas_floor', $fields);
        $this->assertArrayNotHasKey('conversion_event', $fields);
    }

    public function test_accelerated_pacing_needs_bid_cap_and_dayparting_needs_lifetime_budget(): void
    {
        config(['campaign-manager.edit_categories' => ['bid_strategy', 'schedule']]);
        $campaign = $this->campaign();
        $entity = $this->adSet($campaign);
        $this->assertRejected($campaign, $entity, ['pacing_type' => ['no_pacing']], 'pacing_type', 'bid cap');
        $this->assertRejected($campaign, $entity, ['pacing_type' => ['day_parting']], 'pacing_type', 'lifetime');
        $this->assertStringContainsString('lifetime budget', $this->capabilities()->fieldRefusal($entity, 'adset_schedule'));
        $this->assertSame([], $this->writes);
    }

    public function test_budget_boosts_are_created_updated_verified_and_removed_through_the_schedule_edge(): void
    {
        config(['campaign-manager.edit_categories' => ['budget'], 'platforms.guardrails.max_daily_budget' => 500]);
        $this->meta['adsets'][0]['is_budget_schedule_enabled'] = false;
        $campaign = $this->campaign();
        $entity = $this->adSet($campaign);
        $schedule = [
            'budget_value' => 1000, 'budget_value_type' => 'ABSOLUTE',
            'time_start' => now()->startOfHour()->addDays(2)->getTimestamp(), 'time_end' => now()->startOfHour()->addDays(3)->getTimestamp(),
        ];
        $edit = $this->editor()->propose($campaign, $entity, $this->user, ['budget_schedules' => [$schedule]]);
        $edit = $this->editor()->apply($edit, $this->user, acknowledged: true);
        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame('budget_schedules', $this->writes[0]['id']);
        $this->assertSame('7001', $entity->refresh()->settings['budget_schedules'][0]['id']);
        $edit = $this->editor()->propose($campaign, $entity, $this->user, [
            'budget_schedules' => [[...$schedule, 'id' => '7001', 'budget_value' => 2000]],
        ]);
        $this->assertSame(CampaignEntityEdit::Applied, $this->editor()->apply($edit, $this->user, acknowledged: true)->state);
        $this->assertSame('budget_schedules', $this->writes[1]['id']);
        Http::assertSent(fn (Request $request): bool => $request->method() === 'DELETE' && str_ends_with($request->url(), '/7001'));
        $edit = $this->editor()->propose($campaign, $entity->refresh(), $this->user, ['budget_schedules' => []]);
        $this->assertSame(CampaignEntityEdit::Applied, $this->editor()->apply($edit, $this->user, acknowledged: true)->state);
        $this->assertSame([], $entity->refresh()->settings['budget_schedules']);
    }

    public function test_a_failed_schedule_replacement_reports_the_removed_original_in_readback(): void
    {
        config(['campaign-manager.edit_categories' => ['budget'], 'platforms.guardrails.max_daily_budget' => 500]);
        $schedule = [
            'id' => '7001', 'budget_value' => 1000, 'budget_value_type' => 'ABSOLUTE',
            'time_start' => now()->startOfHour()->addDays(2)->getTimestamp(),
            'time_end' => now()->startOfHour()->addDays(3)->getTimestamp(),
        ];
        $this->meta['adsets'][0]['budget_schedules'] = ['data' => [$schedule]];
        $this->meta['adsets'][0]['is_budget_schedule_enabled'] = true;
        $campaign = $this->campaign();
        $entity = $this->adSet($campaign);
        $edit = $this->editor()->propose($campaign, $entity, $this->user, [
            'budget_schedules' => [[...$schedule, 'budget_value' => 2000]],
        ]);
        $this->rejectScheduleCreation = true;
        $edit = $this->editor()->apply($edit, $this->user, acknowledged: true);
        $this->assertSame(CampaignEntityEdit::Failed, $edit->state);
        $this->assertStringContainsString('Partly applied', $edit->error);
        $this->assertStringContainsString('did not reach the requested value', $edit->error);
        $this->assertSame(['budget_schedules' => []], $edit->readback);
        $this->assertSame([], $entity->refresh()->settings['budget_schedules']);
    }
}
