<?php

namespace App\Services\Meet;

use App\Models\Room;
use App\Models\User;
use Carbon\Carbon;

class IcalService
{
    public function forRoom(Room $room, User $host): string
    {
        $start = Carbon::parse($room->scheduled_at ?? now())->utc();
        $end = (clone $start)->addMinutes($room->duration_minutes ?? 60);
        $uid = $room->uuid.'@meet.ladill.com';

        $lines = [
            'BEGIN:VCALENDAR',
            'VERSION:2.0',
            'PRODID:-//Ladill//Meet//EN',
            'CALSCALE:GREGORIAN',
            'METHOD:REQUEST',
            'BEGIN:VEVENT',
            'UID:'.$uid,
            'DTSTAMP:'.$start->format('Ymd\THis\Z'),
            'DTSTART:'.$start->format('Ymd\THis\Z'),
            'DTEND:'.$end->format('Ymd\THis\Z'),
            'SUMMARY:'.$this->escape($room->title),
            'DESCRIPTION:'.$this->escape($room->description ?? 'Join via Ladill Meet'),
            'LOCATION:'.$this->escape($room->joinUrl()),
            'ORGANIZER;CN='.$this->escape($host->name).':MAILTO:'.$host->email,
            'URL:'.$room->joinUrl(),
            'END:VEVENT',
            'END:VCALENDAR',
        ];

        return implode("\r\n", $lines);
    }

    protected function escape(string $value): string
    {
        return str_replace(["\n", ',', ';'], ['\\n', '\\,', '\\;'], $value);
    }
}
