<?php

namespace App\Http\Services;


use App\Models\Platform;
use App\Models\SocialPost;

class PlatformService
{
    public function getPlatformsWithAccounts($workspaceId)
    {
        $platforms = Platform::with([
            'accounts' => function ($q) use ($workspaceId) {
                $q->where('workspace_id', $workspaceId);
            }
        ])->get();

        $platfromWithStat = $platforms->map(function ($platform) {

            $accounts = $platform->accounts;
            return [
                'id' => $platform->id,
                'name' => $platform->name,
                'slug' => $platform->slug,
                'configuration' => $platform->configuration,
                'accounts' => $platform->accounts->map(fn($a) => [
                    'id' => $a->id,
                    'avatar' => $a->avatar_url,
                ]),
                'accountCount' => $platform->accounts->count(),
                'lastSync' => $platform->accounts->max('last_synced_at') ?? 'Never',
                'stats' => $this->calculatePlatformStats($platform->id, $accounts),
            ];
        });

        $overview = [
            ...$this->calculatePlatformStats(null, $platforms->flatMap(fn($p) => $p->accounts)),
            'accounts' => $platforms->flatMap(fn($p) => $p->accounts)->count(),
        ];

        return $platfromData = [
            'overview' => $overview,
            'platforms' => $platfromWithStat
        ];
    }

    protected function calculatePlatformStats($platformId = null, $accounts)
    {
        $accountIds = $accounts->pluck('id');

        $postsQuery = SocialPost::with('metrics')
            ->when($platformId, fn($q) => $q->where('platform_id', $platformId))
            ->whereIn('account_id', $accountIds)
            ->get();

        // Note: metrics is a hasOne relationship (single model, not collection)
        $totals = [
            'followers' => $accounts->sum(fn($a) => $a->followers ?? 0),
            'reach' => $postsQuery->sum(fn($p) => $p->metrics->reach ?? 0),
            'posts' => $postsQuery->count(),
            'engagements' => $postsQuery->sum(fn($p) => $p->metrics->engagements ?? 0),
        ];

        return collect($totals)->map(fn($value) => $this->formatNumber($value))->toArray();
    }


    protected function formatNumber(int $number): string
    {
        if ($number >= 1_000_000)
            return round($number / 1_000_000, 1) . 'M';
        if ($number >= 1_000)
            return round($number / 1_000, 1) . 'K';
        return (string) $number;
    }


    public function setSetting(Platform $platform, array|object $configuration)
    {
        $existing = (array) $platform->configuration;
        $newConfig = array_merge($existing, (array) $configuration);

        $platform->configuration = (object) $newConfig;
        $platform->save();

        return $platform->configuration;
    }




}
