<?php

namespace App\Models;

use App\Models\Concerns\BelongsToOwner;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

class Invitation extends Model
{
    use BelongsToOwner;

    protected $table = 'meet_invitations';

    protected $fillable = [
        'uuid', 'owner_ref', 'room_id', 'email', 'user_ref',
        'display_name', 'role', 'status', 'rsvp_token', 'responded_at',
        'calendar_event_id', 'sent_at',
    ];

    protected function casts(): array
    {
        return [
            'sent_at' => 'datetime',
            'responded_at' => 'datetime',
        ];
    }

    protected static function booted(): void
    {
        static::creating(function (Invitation $invitation) {
            if (empty($invitation->uuid)) {
                $invitation->uuid = (string) Str::uuid();
            }
            if (empty($invitation->rsvp_token)) {
                $invitation->rsvp_token = Str::random(40);
            }
        });
    }

    public function getRouteKeyName(): string
    {
        return 'uuid';
    }

    public function rsvpUrl(): string
    {
        return route('meet.invitations.rsvp', ['invitation' => $this->uuid, 'token' => $this->rsvp_token]);
    }

    public function room(): BelongsTo
    {
        return $this->belongsTo(Room::class, 'room_id');
    }
}
