<?php

namespace App\Services\Meet;

use App\Models\Session;
use Illuminate\Support\Collection;

class AttendanceService
{
    /**
     * @return Collection<int, array<string, mixed>>
     */
    public function forSession(Session $session): Collection
    {
        return $session->participants()
            ->orderBy('joined_at')
            ->get()
            ->map(fn ($p) => [
                'display_name' => $p->display_name,
                'email' => $p->email,
                'role' => $p->role,
                'joined_at' => $p->joined_at?->toIso8601String(),
                'left_at' => $p->left_at?->toIso8601String(),
                'duration_minutes' => ($p->joined_at && $p->left_at)
                    ? (int) $p->joined_at->diffInMinutes($p->left_at)
                    : ($p->joined_at ? (int) $p->joined_at->diffInMinutes(now()) : 0),
            ]);
    }

    public function toCsv(Session $session): string
    {
        $rows = [['Name', 'Email', 'Role', 'Joined', 'Left', 'Duration (min)']];
        foreach ($this->forSession($session) as $row) {
            $rows[] = [
                $row['display_name'],
                $row['email'] ?? '',
                $row['role'],
                $row['joined_at'] ?? '',
                $row['left_at'] ?? '',
                (string) $row['duration_minutes'],
            ];
        }

        return collect($rows)->map(fn ($r) => implode(',', array_map(fn ($c) => '"'.str_replace('"', '""', $c).'"', $r)))->implode("\n");
    }
}
