<?php

namespace App\Http\Controllers;

use App\Models\ServiceCalendarToken;
use App\Services\Calendar\GoogleCalendarService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CalendarController extends Controller
{
    public function __construct(private GoogleCalendarService $google)
    {
    }

    public function connect()
    {
        $authUrl = $this->google->buildAuthUrl();

        return view('calendar.connect', compact('authUrl'));
    }

    public function callback(Request $request)
    {
        if ($code = $request->get('code')) {
            $tokens = $this->google->exchangeAuthCode($code);
            if ($tokens) {
                ServiceCalendarToken::updateOrCreate(
                    ['user_id' => Auth::id(), 'provider' => 'google'],
                    [
                        'access_token' => [
                            'access_token' => $tokens['access_token'] ?? null,
                            'token_type' => $tokens['token_type'] ?? 'Bearer',
                        ],
                        'refresh_token' => $tokens['refresh_token'] ?? null,
                        'expires_at' => isset($tokens['expires_at']) ? $tokens['expires_at'] : null,
                        'scopes' => explode(' ', $tokens['scope'] ?? ''),
                        'remote_calendar_id' => 'primary',
                    ]
                );
            }
        }

        return view('calendar.callback');
    }

    public function storeToken(Request $request)
    {
        $data = $request->validate([
            'provider' => ['required', 'string'],
            'access_token' => ['required', 'string'],
            'refresh_token' => ['nullable', 'string'],
            'expires_at' => ['nullable', 'date'],
            'scopes' => ['nullable', 'array'],
            'remote_calendar_id' => ['nullable', 'string'],
        ]);

        ServiceCalendarToken::updateOrCreate(
            ['user_id' => Auth::id(), 'provider' => $data['provider']],
            [
                'access_token' => json_decode($data['access_token'], true) ?? $data['access_token'],
                'refresh_token' => $data['refresh_token'] ?? null,
                'expires_at' => $data['expires_at'] ?? null,
                'scopes' => $data['scopes'] ?? [],
                'remote_calendar_id' => $data['remote_calendar_id'] ?? null,
            ]
        );

        return back()->with('status', 'Calendar connected.');
    }
}
