<?php

namespace App\Http\Controllers;

use App\Http\Services\PlatformService;
use App\Models\Platform;
use App\Models\SocialAccount;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Inertia\Inertia;

class PlatformController extends Controller
{
    protected $platformService;

    public function __construct(
        PlatformService $platformService
    ) {
        $this->platformService = $platformService;
        $this->user = auth_user();

    }


    public function index()
    {

        $workspaceId = auth_user()->current_workspace_id;
        $platformData = $this->platformService->getPlatformsWithAccounts($workspaceId);


        return Inertia::render("Platform/Index", [
            "platforms" => $platformData['platforms'],
            "overview" => $platformData['overview']
        ]);
    }

    public function setting($id)
    {
        $platform = Platform::findOrFail($id);


        return Inertia::render('Platform/Settings', [
            'platform' => $platform,
            'dynamicFields' => [
                'redirect_uri' => url("/account/{$platform->slug}/callback?medium={$platform->slug}"),
            ]
        ]);

    }

    public function settingStore(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:platforms,id',
            'configuration' => 'required|array',
        ]);

        $platform = Platform::findOrFail($request->input('id'));

        $response = $this->platformService->setSetting($platform, $request->input('configuration'));

        return back()->with('success', 'Settings saved successfully!');
    }

    public function accounts($id)
    {
        $platform = Platform::findOrFail($id);

        $key = request()->input("key");



        $accounts = SocialAccount::where('platform_id', $id)
            ->when($key === 'own', function ($query) {
                $query->where('user_id', auth()->id());
            })
            ->search(['name'])
            ->filter(['status'])
            ->latest()
            ->paginate(paginateNumber());

        $accounts->getCollection()->transform(function ($account) {
            return $this->attachAccountMetrics($account);
        });

        return Inertia::render('Platform/Accounts', [
            'platform' => $platform->only('id', 'name', 'slug', 'configuration'),
            'accounts' => $accounts,
        ]);
    }

    private function attachAccountMetrics($account)
    {
        $account->followers = $account->followers ?? 0;

        $posts = $account->posts()->with('metrics')->get();

        $lastPost = $posts->sortByDesc('created_at')->first();
        $account->last_activity = $lastPost ? $lastPost->created_at->diffForHumans() : 'No activity';

        $now = now();
        // Note: metrics is a hasOne relationship (single model, not collection)
        $lastWeek = $posts
            ->whereBetween('created_at', [$now->copy()->subDays(7), $now])
            ->sum(fn($p) => $p->metrics->engagements ?? 0);

        $prevWeek = $posts
            ->whereBetween('created_at', [$now->copy()->subDays(14), $now->copy()->subDays(7)])
            ->sum(fn($p) => $p->metrics->engagements ?? 0);

        $account->engagement_trend = $prevWeek === 0 ? 'stable' : ($lastWeek > $prevWeek ? 'up' : 'down');

        $account->engagement = $posts->sum(fn($p) => $p->metrics->engagements ?? 0);

        return $account;
    }

    /**
     * Create a new social account entry with label before connection
     */
    public function createAccount(Request $request)
    {
        $request->validate([
            'label' => 'required|string|max:255',
            'platform_id' => 'required|exists:platforms,id',
            'platform_slug' => 'required|string',
        ]);

        $user = auth()->user();
        $workspace = current_workspace();

        // Create social account entry with label
        $account = SocialAccount::create([
            'uid' => Str::uuid(),
            'user_id' => $user->id,
            'workspace_id' => $workspace->id,
            'platform_id' => $request->platform_id,
            'label' => $request->label,
            'is_connected' => '0', // Initially disconnected
            'status' => '1', // Active
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        // Return Inertia response with account data for frontend redirect
        return back()->with([
            'success' => 'Account label created successfully. Ready to connect!',
            'account' => $account->only(['id', 'uid', 'label'])
        ]);
    }

}
