<?php

namespace App\Libraries\VideoMeeting;

use GuzzleHttp\Client;

/**
 * Google Meet links are created as a side effect of a Calendar API event
 * with conferenceData.createRequest — there's no standalone "create a Meet
 * link" endpoint. Uses a service account with domain-wide delegation
 * (typical for a platform creating events on behalf of agency users) rather
 * than per-user OAuth.
 */
class GoogleMeetAdapter implements VideoMeetingInterface
{
    private Client $http;
    private string $accessToken;
    private string $calendarId;

    public function __construct()
    {
        // Service-account token acquisition (JWT bearer flow) is assumed
        // handled by a shared GoogleAuthService and injected here; kept
        // minimal to focus on the Meet-specific request shape.
        $this->accessToken = env('google.serviceAccountAccessToken') ?? '';
        $this->calendarId  = env('google.calendarId') ?? 'primary';
        $this->http = new Client();
    }

    public function createMeeting(string $topic, string $startTime, int $durationMinutes): array
    {
        $endTime = date('c', strtotime($startTime) + ($durationMinutes * 60));
        $requestId = bin2hex(random_bytes(8));

        $response = $this->http->post(
            "https://www.googleapis.com/calendar/v3/calendars/{$this->calendarId}/events",
            [
                'headers' => ['Authorization' => "Bearer {$this->accessToken}"],
                'query'   => ['conferenceDataVersion' => 1],
                'json'    => [
                    'summary' => $topic,
                    'start'   => ['dateTime' => $startTime],
                    'end'     => ['dateTime' => $endTime],
                    'conferenceData' => [
                        'createRequest' => [
                            'requestId'             => $requestId,
                            'conferenceSolutionKey'  => ['type' => 'hangoutsMeet'],
                        ],
                    ],
                ],
            ]
        );

        $body = json_decode((string) $response->getBody(), true);

        return [
            'external_meeting_id' => $body['id'],
            'join_url'            => $body['hangoutLink'] ?? ($body['conferenceData']['entryPoints'][0]['uri'] ?? null),
            'start_url'           => null, // Google Meet has no separate host-start URL
        ];
    }

    public function cancelMeeting(string $externalMeetingId): bool
    {
        $response = $this->http->delete(
            "https://www.googleapis.com/calendar/v3/calendars/{$this->calendarId}/events/{$externalMeetingId}",
            ['headers' => ['Authorization' => "Bearer {$this->accessToken}"]]
        );
        return $response->getStatusCode() < 300;
    }
}
