<?php

namespace App\Libraries\VideoMeeting;

use GuzzleHttp\Client;

/**
 * Uses Zoom's Server-to-Server OAuth app type (account-level credentials,
 * no per-user consent flow needed) — appropriate for a platform scheduling
 * meetings on behalf of agencies rather than end users authorizing
 * individually.
 */
class ZoomMeetingAdapter implements VideoMeetingInterface
{
    private Client $http;
    private string $accountId;
    private string $clientId;
    private string $clientSecret;

    public function __construct()
    {
        $this->accountId    = env('zoom.accountId') ?? '';
        $this->clientId     = env('zoom.clientId') ?? '';
        $this->clientSecret = env('zoom.clientSecret') ?? '';
        $this->http = new Client();
    }

    private function accessToken(): string
    {
        $response = $this->http->post('https://zoom.us/oauth/token', [
            'auth'        => [$this->clientId, $this->clientSecret],
            'form_params' => ['grant_type' => 'account_credentials', 'account_id' => $this->accountId],
        ]);
        $body = json_decode((string) $response->getBody(), true);
        return $body['access_token'];
    }

    public function createMeeting(string $topic, string $startTime, int $durationMinutes): array
    {
        $token = $this->accessToken();

        $response = $this->http->post('https://api.zoom.us/v2/users/me/meetings', [
            'headers' => ['Authorization' => "Bearer {$token}"],
            'json'    => [
                'topic'      => $topic,
                'type'       => 2, // scheduled meeting
                'start_time' => $startTime,
                'duration'   => $durationMinutes,
                'settings'   => ['join_before_host' => true, 'waiting_room' => true],
            ],
        ]);

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

        return [
            'external_meeting_id' => (string) $body['id'],
            'join_url'            => $body['join_url'],
            'start_url'           => $body['start_url'] ?? null,
        ];
    }

    public function cancelMeeting(string $externalMeetingId): bool
    {
        $token = $this->accessToken();
        $response = $this->http->delete("https://api.zoom.us/v2/meetings/{$externalMeetingId}", [
            'headers' => ['Authorization' => "Bearer {$token}"],
        ]);
        return $response->getStatusCode() < 300;
    }
}
