<?php

namespace App\Models\Juil;

use App\Models\User;
use App\Traits\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class MeetingMinute extends Model
{
    use BelongsToTenant, SoftDeletes;

    protected $table = 'meeting_minutes';

    const STATUS_DRAFT = 'DRAFT';

    const STATUS_RECORDING = 'RECORDING';

    const STATUS_PROCESSING = 'PROCESSING';

    const STATUS_COMPLETED = 'COMPLETED';

    const STATUS_FAILED = 'FAILED';

    protected $fillable = [
        'tenant_id',
        'user_id',
        'title',
        'folder',
        'participants',
        'meeting_date',
        'meeting_time',
        'duration_seconds',
        'audio_file_path',
        'audio_gcs_uri',
        'audio_file_size',
        'full_transcript',
        'summary',
        'decisions',
        'action_items',
        'status',
        'stt_language',
    ];

    protected $casts = [
        'participants' => 'array',
        'decisions' => 'array',
        'action_items' => 'array',
        'meeting_date' => 'date',
        'duration_seconds' => 'integer',
        'audio_file_size' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function segments(): HasMany
    {
        return $this->hasMany(MeetingMinuteSegment::class)->orderBy('segment_order');
    }

    public function getFormattedDurationAttribute(): string
    {
        $seconds = $this->duration_seconds;
        $hours = floor($seconds / 3600);
        $minutes = floor(($seconds % 3600) / 60);
        $secs = $seconds % 60;

        if ($hours > 0) {
            return sprintf('%d:%02d:%02d', $hours, $minutes, $secs);
        }

        return sprintf('%02d:%02d', $minutes, $secs);
    }
}
