<?php

namespace App\Models;

use App\Enums\ActivityTypeEnum;
use App\Enums\ApprovalStatusEnum;
use App\Enums\PublishStatusEnum;
use App\Events\ActivityLogged;
use App\Events\RouteArticleApproved;
use Database\Factories\RouteArticleFactory;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Carbon;

/**
 * @property int $id
 * @property int $feed_id
 * @property int $platform_channel_id
 * @property int $article_id
 * @property ApprovalStatusEnum $approval_status
 * @property PublishStatusEnum $publish_status
 * @property int $publish_attempts
 * @property Carbon|null $next_attempt_at
 * @property Carbon|null $validated_at
 * @property Carbon $created_at
 * @property Carbon $updated_at
 */
class RouteArticle extends Model
{
    /** @use HasFactory<RouteArticleFactory> */
    use HasFactory;

    protected $fillable = [
        'feed_id',
        'platform_channel_id',
        'article_id',
        'approval_status',
        'publish_status',
        'publish_attempts',
        'next_attempt_at',
        'validated_at',
    ];

    protected $casts = [
        'approval_status' => ApprovalStatusEnum::class,
        'publish_status' => PublishStatusEnum::class,
        'publish_attempts' => 'integer',
        'next_attempt_at' => 'datetime',
        'validated_at' => 'datetime',
    ];

    /**
     * @return BelongsTo<Route, $this>
     */
    public function route(): BelongsTo
    {
        return $this->belongsTo(Route::class, 'feed_id', 'feed_id')
            ->where('platform_channel_id', $this->platform_channel_id);
    }

    /**
     * @return BelongsTo<Article, $this>
     */
    public function article(): BelongsTo
    {
        return $this->belongsTo(Article::class);
    }

    /**
     * @return BelongsTo<Feed, $this>
     */
    public function feed(): BelongsTo
    {
        return $this->belongsTo(Feed::class);
    }

    /**
     * @return BelongsTo<PlatformChannel, $this>
     */
    public function platformChannel(): BelongsTo
    {
        return $this->belongsTo(PlatformChannel::class);
    }

    public function isPending(): bool
    {
        return $this->approval_status === ApprovalStatusEnum::PENDING;
    }

    public function isApproved(): bool
    {
        return $this->approval_status === ApprovalStatusEnum::APPROVED;
    }

    public function isRejected(): bool
    {
        return $this->approval_status === ApprovalStatusEnum::REJECTED;
    }

    public function approve(): void
    {
        if ($this->isApproved()) {
            return;
        }

        $this->update(['approval_status' => ApprovalStatusEnum::APPROVED]);

        ActivityLogged::dispatch(
            ActivityTypeEnum::APPROVE,
            "Approved \"{$this->article->title}\"",
            ['route_article_id' => $this->id],
            $this->article,
        );

        event(new RouteArticleApproved($this));
    }

    public function reject(): void
    {
        if ($this->isRejected()) {
            return;
        }

        $this->update(['approval_status' => ApprovalStatusEnum::REJECTED]);

        ActivityLogged::dispatch(
            ActivityTypeEnum::REJECT,
            "Rejected \"{$this->article->title}\"",
            ['route_article_id' => $this->id],
            $this->article,
        );
    }

    private const RETRY_BACKOFF_MINUTES = [5, 30, 120, 360];

    public const MAX_PUBLISH_ATTEMPTS = 4;

    public function recordPublishAttemptFailed(): void
    {
        $attempts = $this->publish_attempts + 1;
        $backoff = self::RETRY_BACKOFF_MINUTES;

        $this->update([
            'publish_attempts' => $attempts,
            'next_attempt_at' => now()->addMinutes($backoff[$attempts - 1] ?? end($backoff)),
        ]);
    }

    public function clearPublishAttempts(): void
    {
        $this->update(['publish_attempts' => 0, 'next_attempt_at' => null]);
    }

    public function hasExhaustedPublishAttempts(): bool
    {
        return $this->publish_attempts >= self::MAX_PUBLISH_ATTEMPTS;
    }

    /**
     * @param  Builder<RouteArticle>  $query
     * @return Builder<RouteArticle>
     */
    public function scopeDueForPublishing(Builder $query): Builder
    {
        return $query->where('publish_attempts', '<', self::MAX_PUBLISH_ATTEMPTS)
            ->where(function (Builder $query) {
                $query->whereNull('next_attempt_at')
                    ->orWhere('next_attempt_at', '<=', now());
            });
    }
}
