<?php

namespace Tests\Feature;

use App\Campaigns\Manager\CampaignSynchronizer;
use App\Campaigns\Manager\Editing\EditCapabilities;
use App\Campaigns\Manager\Editing\EditRefused;
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 App\Services\GoogleAdsService;
use App\Services\LinkedIn\LinkedIn;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Validation\ValidationException;
use Livewire\Livewire;
use Mockery;
use Tests\TestCase;

/**
 * End dates changed from the campaign manager.
 *
 * The end is entered in the zone the platform reports the object in, sent in
 * a form that cannot be read in another zone, and compared as a moment. A
 * total budget is re-checked over the new length.
 */
class CampaignManagerScheduleEditTest 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 = [];

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

        $this->travelTo('2026-06-01 12:00:00');

        config([
            'platforms.meta.token' => 'test-token',
            'platforms.meta.mcp.enabled' => false,
            'platforms.guardrails.allowed_ad_accounts' => ['meta:*', 'linkedin:*', 'google:*'],
            'platforms.guardrails.paused' => false,
            'platforms.guardrails.change_cooldown_seconds' => 0,
            'platforms.guardrails.max_changes_per_day' => 50,
            'platforms.guardrails.budget_ceiling_currency' => 'USD',
            'platforms.guardrails.max_daily_budget' => 500,
            'platforms.guardrails.confirm_daily_budget_above' => 200,
            'campaign-manager.edit_platforms' => ['meta', 'linkedin', 'google'],
            'campaign-manager.edit_categories' => ['name', 'budget', 'bid', 'schedule'],
            'services.google_ads.refresh_token' => 'token',
            'services.google_ads.customer_id' => '3460855874',
        ]);

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

        $this->meta['campaign'] = [
            'id' => '120252047635070626', 'name' => 'Winter Sale', 'status' => 'ACTIVE',
            'effective_status' => 'ACTIVE', 'objective' => 'OUTCOME_SALES', 'account_id' => '111',
        ];
        $this->meta['adsets'] = [[
            'id' => '2001', 'name' => 'US mobile', 'status' => 'ACTIVE', 'daily_budget' => '2500', 'bid_strategy' => 'LOWEST_COST_WITHOUT_CAP',
            'start_time' => '2026-05-20T00:00:00-0700', 'end_time' => '2026-06-30T23:00:00-0700',
        ]];

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

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

                foreach ($this->meta['adsets'] as $i => $row) {
                    if ($row['id'] === $id) {
                        // Meta echoes times back in its own format, not as sent.
                        $echo = array_map(
                            fn (string $time): string => date_create($time)->format('Y-m-d\TH:i:sO'),
                            array_intersect_key($fields, ['start_time' => true, 'end_time' => true]),
                        );
                        $this->meta['adsets'][$i] = [...$row, ...$fields, ...$echo];
                    }
                }

                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(array $attributes = []): 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',
            ...$attributes,
        ]);

        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);
    }

    /** @param  array<string, mixed>  $values */
    private function assertRejected(Campaign $campaign, CampaignPlatformEntity $entity, array $values, string $message, string $field = 'end_time'): 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_a_meta_ad_set_end_is_entered_in_the_account_zone_and_sent_with_its_offset(): void
    {
        $campaign = $this->campaign();
        $adSet = $this->adSet($campaign);

        $this->assertContains('end_time', $this->capabilities()->editableFields($adSet));
        $this->assertSame('2026-06-30T23:00', EditCapabilities::inputMoment($adSet, EditCapabilities::current($adSet, 'end_time')));

        $edit = $this->editor()->propose($campaign, $adSet, $this->user, ['end_time' => '2026-07-15T18:30']);

        $this->assertSame(['end_time' => ['before' => '2026-06-30T23:00:00-0700', 'after' => '2026-07-15T18:30:00-0700']], $edit->changes);
        $this->assertSame([], $this->capabilities()->confirmations($adSet, $edit->changes));

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

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame([['id' => '2001', 'fields' => ['end_time' => '2026-07-15T18:30:00-07:00']]], $this->writes);
        $this->assertSame(['end_time' => '2026-07-15T18:30:00-0700'], $edit->readback);
    }

    public function test_ends_too_soon_or_before_the_start_are_rejected(): void
    {
        $this->meta['adsets'][0]['start_time'] = '2026-06-10T00:00:00-0700';
        $campaign = $this->campaign();
        $adSet = $this->adSet($campaign);

        $this->assertRejected($campaign, $adSet, ['end_time' => 'next week'], 'Enter a date and time');
        $this->assertRejected($campaign, $adSet, ['end_time' => '2026-06-01T05:30'], 'at least 60 minutes from now');
        $this->assertRejected($campaign, $adSet, ['end_time' => '2026-06-09T12:00'], 'more than an hour after the start');
        $this->assertSame([], $this->writes);
    }

    public function test_a_lifetime_budget_is_rechecked_over_the_new_length_and_the_repacing_acknowledged(): void
    {
        $this->meta['adsets'][0] = [...$this->meta['adsets'][0], 'daily_budget' => '0', 'lifetime_budget' => '300000',
            'start_time' => '2026-06-01T00:00:00-0700', 'end_time' => '2026-06-30T00:00:00-0700'];
        $campaign = $this->campaign();
        $adSet = $this->adSet($campaign);

        // 3,000 over 5 days is 600 a day, above the 500 ceiling.
        $this->assertRejected($campaign, $adSet, ['end_time' => '2026-06-06T00:00'], 'total budget would not fit');

        $edit = $this->editor()->propose($campaign, $adSet, $this->user, ['end_time' => '2026-06-16T00:00']);
        $notes = $this->capabilities()->confirmations($adSet, $edit->changes);

        $this->assertStringContainsString('spread over 15 days instead of 29', $notes[0]);
        $this->assertStringContainsString('200.00 USD a day instead of 103.45', $notes[0]);

        try {
            $this->editor()->apply($edit, $this->user);
            $this->fail('Sent without acknowledgement.');
        } catch (EditRefused $exception) {
            $this->assertStringContainsString('needs to be acknowledged', $exception->getMessage());
        }

        $this->assertSame([], $this->writes);
        $this->assertSame(CampaignEntityEdit::Applied, $this->editor()->apply($edit->refresh(), $this->user, acknowledged: true)->state);
    }

    public function test_an_ended_run_and_a_switched_off_category_are_shown_as_locked(): void
    {
        $this->meta['adsets'][0]['end_time'] = '2026-05-25T00:00:00-0700';
        $adSet = $this->adSet($this->campaign());

        $this->assertStringContainsString('already ended', $this->capabilities()->lockedFields($adSet)['end_time']);

        config(['campaign-manager.edit_categories' => ['name', 'budget']]);
        $this->assertStringContainsString('Schedule changes are not switched on', $this->capabilities()->lockedFields($adSet)['end_time']);
    }

    public function test_a_linkedin_end_is_sent_with_the_reported_start_kept(): void
    {
        $start = 1780272000000; // 2026-06-01 00:00 UTC
        $live = ['id' => 555, 'name' => 'Lead gen', 'status' => 'ACTIVE', 'campaignGroup' => 'urn:li:sponsoredCampaignGroup:44',
            'dailyBudget' => ['amount' => '50.00', 'currencyCode' => 'USD'], 'runSchedule' => ['start' => $start, 'end' => 1782864000000]];

        $linkedin = Mockery::mock(LinkedIn::class);
        $linkedin->shouldReceive('campaignConversions')->andReturn([]);
        $linkedin->shouldReceive('on')->andReturnSelf();
        $linkedin->shouldReceive('campaign')->andReturnUsing(function () use (&$live): array {
            return $live;
        });
        $linkedin->shouldReceive('campaignGroup')->andReturn(['id' => 44, 'name' => 'Q4', 'status' => 'ACTIVE']);
        $linkedin->shouldReceive('creatives')->andReturn(['elements' => [], 'next_page_token' => null]);
        $linkedin->shouldReceive('updateEntity')->once()
            ->with('urn:li:sponsoredAccount:999', 'campaign', '555', ['runSchedule' => ['start' => $start, 'end' => 1784116800000]])
            ->andReturnUsing(function () use (&$live): void {
                $live['runSchedule']['end'] = 1784116800000;
            });
        $this->app->instance(LinkedIn::class, $linkedin);

        $campaign = $this->campaign(['platform' => 'linkedin', 'ad_account_id' => 'urn:li:sponsoredAccount:999', 'external_campaign_id' => '555']);
        $entity = $campaign->platformEntities()->where('external_id', '555')->sole();

        $edit = $this->editor()->apply($this->editor()->propose($campaign, $entity, $this->user, ['end_time' => '2026-07-15T12:00']), $this->user);

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertEquals(['end_time' => 1784116800000], $edit->readback);
    }

    public function test_a_meta_start_still_ahead_is_moved_and_one_that_has_passed_is_locked(): void
    {
        $this->assertStringContainsString('has already started, and Meta does not move a start that has passed',
            $this->capabilities()->lockedFields($this->adSet($this->campaign()))['start_time']);

        $this->meta['adsets'][0]['start_time'] = '2026-06-10T00:00:00-0700';
        $campaign = $this->campaign();
        $adSet = $this->adSet($campaign);

        $this->assertContains('start_time', $this->capabilities()->editableFields($adSet));
        $this->assertSame('Delivery begins at this time, in UTC-07:00 as Meta reports it.', $this->capabilities()->hint($adSet, 'start_time'));

        $edit = $this->editor()->apply($this->editor()->propose($campaign, $adSet, $this->user, ['start_time' => '2026-06-12T09:00']), $this->user);

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame([['id' => '2001', 'fields' => ['start_time' => '2026-06-12T09:00:00-07:00']]], $this->writes);
    }

    public function test_a_start_and_end_moved_together_are_checked_against_each_other(): void
    {
        $this->meta['adsets'][0]['start_time'] = '2026-06-10T00:00:00-0700';
        $campaign = $this->campaign();
        $adSet = $this->adSet($campaign);

        $this->assertRejected($campaign, $adSet, ['start_time' => '2026-07-05T00:00'], 'more than an hour before the end', 'start_time');
        $this->assertRejected($campaign, $adSet, ['start_time' => '2026-07-05T00:00', 'end_time' => '2026-07-05T00:30'], 'more than an hour after the start');

        $edit = $this->editor()->propose($campaign, $adSet, $this->user, ['start_time' => '2026-07-05T00:00', 'end_time' => '2026-07-20T00:00']);
        $edit = $this->editor()->apply($edit, $this->user);

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame(['start_time' => '2026-07-05T00:00:00-07:00', 'end_time' => '2026-07-20T00:00:00-07:00'], $this->writes[0]['fields']);
    }

    public function test_a_later_start_repaces_a_lifetime_budget_in_one_note(): void
    {
        $this->meta['adsets'][0] = [...$this->meta['adsets'][0], 'daily_budget' => '0', 'lifetime_budget' => '300000',
            'start_time' => '2026-06-10T00:00:00-0700', 'end_time' => '2026-06-30T00:00:00-0700'];
        $campaign = $this->campaign();
        $adSet = $this->adSet($campaign);

        $this->assertRejected($campaign, $adSet, ['start_time' => '2026-06-26T00:00'], 'With this start, the total budget would not fit', 'start_time');

        $edit = $this->editor()->propose($campaign, $adSet, $this->user, ['start_time' => '2026-06-20T00:00', 'end_time' => '2026-07-10T00:00']);
        $notes = $this->capabilities()->confirmations($adSet, $edit->changes);

        $this->assertCount(1, $notes);
        $this->assertStringContainsString('spread over 20 days instead of 20', $notes[0]);

        $edit = $this->editor()->propose($campaign, $adSet, $this->user, ['start_time' => '2026-06-20T00:00']);
        $this->assertStringContainsString('spread over 10 days instead of 20', $this->capabilities()->confirmations($adSet, $edit->changes)[0]);
    }

    public function test_a_linkedin_start_keeps_an_open_end_open(): void
    {
        $live = ['id' => 555, 'name' => 'Lead gen', 'status' => 'PAUSED', 'campaignGroup' => 'urn:li:sponsoredCampaignGroup:44',
            'dailyBudget' => ['amount' => '50.00', 'currencyCode' => 'USD'], 'runSchedule' => ['start' => 1781049600000]];

        $linkedin = Mockery::mock(LinkedIn::class);
        $linkedin->shouldReceive('campaignConversions')->andReturn([]);
        $linkedin->shouldReceive('on')->andReturnSelf();
        $linkedin->shouldReceive('campaign')->andReturnUsing(function () use (&$live): array {
            return $live;
        });
        $linkedin->shouldReceive('campaignGroup')->andReturn(['id' => 44, 'name' => 'Q4', 'status' => 'ACTIVE']);
        $linkedin->shouldReceive('creatives')->andReturn(['elements' => [], 'next_page_token' => null]);
        $linkedin->shouldReceive('updateEntity')->once()
            ->with('urn:li:sponsoredAccount:999', 'campaign', '555', ['runSchedule' => ['start' => 1781222400000]])
            ->andReturnUsing(function () use (&$live): void {
                $live['runSchedule']['start'] = 1781222400000;
            });
        $this->app->instance(LinkedIn::class, $linkedin);

        $campaign = $this->campaign(['platform' => 'linkedin', 'ad_account_id' => 'urn:li:sponsoredAccount:999', 'external_campaign_id' => '555']);
        $entity = $campaign->platformEntities()->where('external_id', '555')->sole();

        $edit = $this->editor()->apply($this->editor()->propose($campaign, $entity, $this->user, ['start_time' => '2026-06-12T00:00']), $this->user);

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
    }

    public function test_settings_meta_fixes_and_settings_not_yet_editable_say_why(): void
    {
        $this->meta['adsets'][0] += ['destination_type' => 'WEBSITE', 'targeting' => ['geo_locations' => ['countries' => ['US']]], 'frequency_control_specs' => null];
        $locked = $this->capabilities()->lockedFields($this->adSet($this->campaign()));

        $this->assertStringContainsString('Meta fixes where an ad set sends people', $locked['destination_type']);
        $this->assertStringContainsString('Meta removed detailed-targeting exclusions', $locked['exclusions']);
        $this->assertArrayNotHasKey('frequency_control_specs', $locked);
    }

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

        Livewire::actingAs($this->user)
            ->test(EditEntity::class, ['campaign' => $campaign, 'entity' => $this->adSet($campaign)])
            ->assertSet('values.end_time', '2026-06-30T23:00')
            ->assertSeeHtml('type="datetime-local"')
            ->assertSee('UTC-07:00')
            ->set('values.end_time', '2026-07-15T18:30')
            ->call('review')
            ->assertHasNoErrors()
            ->assertSee('Jun 30, 2026 11:00 PM (UTC-07:00)')
            ->assertSee('Jul 15, 2026 6:30 PM (UTC-07:00)')
            ->assertSee('+15 days')
            ->set('acknowledged', true)
            ->call('confirm')
            ->assertSee('Done.');
    }

    // ---------------------------------------------------------------- Google

    /** @param  array<string, mixed>  $profile */
    private function google(array &$profile): Mockery\MockInterface
    {
        $google = Mockery::mock(GoogleAdsService::class)->makePartial();
        $google->shouldReceive('readManagerCriteria')->andReturn([]);
        $google->shouldReceive('readCampaignProfile')->andReturnUsing(function () use (&$profile): array {
            return $profile;
        });
        $google->shouldReceive('readCampaignStructure')->andReturn(['ad_groups' => [], 'ads' => [], 'asset_groups' => []]);
        $this->app->instance(GoogleAdsService::class, $google);

        return $google;
    }

    /** @return array<string, mixed> */
    private function googleProfile(array $overrides = []): array
    {
        return ['id' => '987', 'name' => 'Search', 'status' => 'ENABLED', 'advertising_channel_type' => 'SEARCH',
            'time_zone' => 'America/New_York', 'start_date_time' => '2026-05-20 00:00:00', 'end_date_time' => '', ...$overrides];
    }

    private function googleCampaign(): Campaign
    {
        return $this->campaign(['platform' => 'google', 'ad_account_id' => '3460855874', 'external_campaign_id' => '987']);
    }

    public function test_a_google_end_is_set_in_the_account_zone_and_only_the_end_is_sent(): void
    {
        $profile = $this->googleProfile();
        $google = $this->google($profile);
        $google->shouldReceive('updateLiveCampaign')->once()
            ->withArgs(fn ($connection, string $id, array $fields): bool => $id === '987' && $fields === ['endDateTime' => '2026-07-15 18:30:00'])
            ->andReturnUsing(function ($connection, string $id, array $fields) use (&$profile): void {
                $profile['end_date_time'] = $fields['endDateTime'];
            });

        $campaign = $this->googleCampaign();
        $entity = $campaign->platformEntities()->where('external_id', '987')->sole();

        $this->assertSame('2026-05-20T00:00:00-0400', EditCapabilities::current($entity, 'start_time'));
        $this->assertNull(EditCapabilities::current($entity, 'end_time'));
        $this->assertStringContainsString('already started', $this->capabilities()->lockedFields($entity)['start_time']);
        $this->assertContains('end_time', $this->capabilities()->editableFields($entity));
        $this->assertSame('Jul 15, 2026 6:30 PM (America/New_York)', EditCapabilities::showMoment($entity, '2026-07-15T18:30:00-0400'));

        $edit = $this->editor()->propose($campaign, $entity, $this->user, ['end_time' => '2026-07-15T18:30']);
        $this->assertSame(['end_time' => ['before' => null, 'after' => '2026-07-15T18:30:00-0400']], $edit->changes);

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

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame(['end_time' => '2026-07-15T18:30:00-0400'], $edit->readback);
    }

    public function test_a_google_start_still_ahead_moves_with_the_end_in_one_call(): void
    {
        $profile = $this->googleProfile(['start_date_time' => '2026-06-10 00:00:00', 'end_date_time' => '2026-06-30 23:59:59']);
        $google = $this->google($profile);
        $google->shouldReceive('updateLiveCampaign')->once()
            ->withArgs(fn ($connection, string $id, array $fields): bool => $fields === ['startDateTime' => '2026-06-20 09:00:00', 'endDateTime' => '2026-07-20 23:59:00'])
            ->andReturnUsing(function ($connection, string $id, array $fields) use (&$profile): void {
                $profile['start_date_time'] = $fields['startDateTime'];
                $profile['end_date_time'] = $fields['endDateTime'];
            });

        $campaign = $this->googleCampaign();
        $entity = $campaign->platformEntities()->where('external_id', '987')->sole();

        $this->assertRejected($campaign, $entity, ['end_time' => ''], 'end time field is required');

        $edit = $this->editor()->propose($campaign, $entity, $this->user, ['start_time' => '2026-06-20T09:00', 'end_time' => '2026-07-20T23:59']);

        $this->assertSame(CampaignEntityEdit::Applied, $this->editor()->apply($edit, $this->user, acknowledged: true)->state);
    }

    public function test_a_google_account_without_a_reported_zone_leaves_its_dates_to_google(): void
    {
        $profile = $this->googleProfile(['time_zone' => '']);
        $this->google($profile)->shouldNotReceive('updateLiveCampaign');

        $campaign = $this->googleCampaign();
        $entity = $campaign->platformEntities()->where('external_id', '987')->sole();

        $this->assertNull(EditCapabilities::current($entity, 'start_time'));
        $this->assertStringContainsString('time zone', $this->capabilities()->lockedFields($entity)['end_time']);
    }
}
