<?php

namespace App\Services\Sync;

use App\Models\PlatformConnection;

class PlatformSyncManager
{
    public function __construct(
        private readonly GoogleAdsSyncService $googleAds,
        private readonly MetaAdsSyncService $metaAds,
        private readonly SearchConsoleSyncService $searchConsole,
        private readonly Ga4SyncService $ga4,
    ) {}

    public function syncConnection(PlatformConnection $connection, string $from, string $to): SyncResult
    {
        $connection->loadMissing('secureCredential');

        $result = match ($connection->platform) {
            'google_ads' => $this->googleAds->sync($connection, $from, $to),
            'meta_ads' => $this->metaAds->sync($connection, $from, $to),
            'search_console' => $this->searchConsole->sync($connection, $from, $to),
            'ga4' => $this->ga4->sync($connection, $from, $to),
            default => SyncResult::failed('Desteklenmeyen platform: '.$connection->platform),
        };

        $meta = $connection->meta ?? [];
        $meta['last_sync_result'] = $result->toArray();
        $meta['last_sync_range'] = ['from' => $from, 'to' => $to];

        $connection->forceFill([
            'status' => $result->ok ? 'active' : 'error',
            'last_sync_at' => now(),
            'last_error' => $result->ok ? null : $result->error,
            'meta' => $meta,
        ])->save();

        return $result;
    }
}
