<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ScheduledPostAttempt extends Model
{
    use HasFactory;

    protected $fillable = [
        'scheduled_post_id',
        'social_account_id',
        'provider',
        'request_payload',
        'response_summary',
        'status',
        'error_message',
    ];

    protected $casts = [
        'request_payload' => 'array',
        'response_summary' => 'array',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /**
     * Get the scheduled post that owns this attempt.
     */
    public function scheduledPost()
    {
        return $this->belongsTo(ScheduledPost::class);
    }

    /**
     * Get the social account for this attempt.
     */
    public function socialAccount()
    {
        return $this->belongsTo(SocialAccount::class);
    }

    /**
     * Mark the attempt as successful.
     */
    public function markSuccessful(array $responseSummary): void
    {
        $this->status = 'success';
        $this->response_summary = $responseSummary;
        $this->save();
    }

    /**
     * Mark the attempt as failed.
     */
    public function markFailed(string $errorMessage, array $responseSummary = null): void
    {
        $this->status = 'failed';
        $this->error_message = $errorMessage;
        if ($responseSummary) {
            $this->response_summary = $responseSummary;
        }
        $this->save();
    }
}