<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class WatchHistory extends Model
{
    protected $table = 'watch_history';

    protected $fillable = [
        'user_id',
        'content_type',
        'content_id',
        'watched_seconds',
        'total_seconds',
        'completed',
        'watched_at',
    ];

    protected $casts = [
        'completed'   => 'boolean',
        'watched_at'  => 'datetime',
    ];

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

    // Dynamically resolve the content model based on content_type
    public function getContentAttribute(): ?Model
    {
        return match ($this->content_type) {
            'video'  => Video::find($this->content_id),
            'tv'     => Tv::find($this->content_id),
            'slider' => Slider::find($this->content_id),
            default  => null,
        };
    }

    // Progress percentage 0-100
    public function getProgressAttribute(): int
    {
        if ($this->total_seconds <= 0) return 0;
        return (int) min(100, round(($this->watched_seconds / $this->total_seconds) * 100));
    }
}
