<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;

class ImageProcessingStatus extends Model
{
	protected $table = 'image_processing_status';
	
	protected $fillable = [
		'batch_job_id',
		'job_id',
		'image_id',
		'prompt',
		'image_path',
		'status',
		'retry_count',
		'error_message',
		'metadata',
		'started_at',
		'completed_at'
	];
	
	protected $casts = [
		'metadata'     => 'array',
		'started_at'   => 'datetime',
		'completed_at' => 'datetime'
	];
	
	// Status constants
	const STATUS_PENDING = 'pending';
	const STATUS_PROCESSING = 'processing';
	const STATUS_COMPLETED = 'completed';
	const STATUS_FAILED = 'failed';
	const STATUS_RETRYING = 'retrying';
	
	/**
	 * Scope to get records by batch job ID
	 */
	public function scopeByBatchJob($query, string $batchJobId)
	{
		return $query->where('batch_job_id', $batchJobId);
	}
	
	/**
	 * Scope to get records by status
	 */
	public function scopeByStatus($query, string $status)
	{
		return $query->where('status', $status);
	}
	
	/**
	 * Scope to get failed records that can be retried
	 */
	public function scopeRetryable($query, int $maxRetries = 3)
	{
		return $query->where('status', self::STATUS_FAILED)
			->where('retry_count', '<', $maxRetries);
	}
	
	/**
	 * Mark as processing
	 */
	public function markAsProcessing(): void
	{
		$this->update([
			'status'     => self::STATUS_PROCESSING,
			'started_at' => now()
		]);
	}
	
	/**
	 * Mark as completed
	 */
	public function markAsCompleted(string $imagePath, array $metadata = []): void
	{
		$this->update([
			'status'        => self::STATUS_COMPLETED,
			'image_path'    => $imagePath,
			'metadata'      => $metadata,
			'completed_at'  => now(),
			'error_message' => null
		]);
	}
	
	/**
	 * Mark as failed
	 */
	public function markAsFailed(string $errorMessage): void
	{
		$this->update([
			'status'        => self::STATUS_FAILED,
			'error_message' => $errorMessage,
			'retry_count'   => $this->retry_count + 1
		]);
	}
	
	/**
	 * Mark as retrying
	 */
	public function markAsRetrying(): void
	{
		$this->update([
			'status'      => self::STATUS_RETRYING,
			'retry_count' => $this->retry_count + 1
		]);
	}
	
	/**
	 * Check if record can be retried
	 */
	public function canRetry(int $maxRetries = 3): bool
	{
		return $this->retry_count < $maxRetries;
	}
	
	/**
	 * Get the full image URL
	 */
	protected function imageUrl(): Attribute
	{
		return Attribute::make(
			get: fn() => $this->image_path ? asset($this->image_path) : null,
		);
	}
}
