<?php

namespace Mtc\Plugins\Wisebee\Classes\Handlers;

use Mtc\Plugins\Wisebee\Classes\Models\WisebeeTranscript;
use Wisebee\Resources\Transcription as RemoteTranscription;

class TranscriptHandler extends BaseHandler
{
    const RESOURCE_NAME = 'transcription';

    /**
     * Whenever a transcription notify arrives from Wisebee, pull the resource
     * by id and persist it via the shared upsert path (FR-014).
     */
    protected function handleTranscript($post): void
    {
        if (empty($post->id)) {
            return;
        }

        /** @var RemoteTranscription $remote */
        $remote = $this->wisebee->get(RemoteTranscription::class, $post->id);
        if (empty($remote)) {
            return;
        }

        $this->upsertTranscript($remote);
    }

    /**
     * Upserts a remote transcription into the local mirror. Idempotent: the
     * unique index on wisebee_id makes repeat pulls safe (FR-015, FR-022).
     * Shared between live webhook delivery and backfill.
     */
    public function upsertTranscript(RemoteTranscription $remote): WisebeeTranscript
    {
        return WisebeeTranscript::updateOrCreate(
            ['wisebee_id' => $remote->id],
            [
                'wisebee_consultation_id' => $remote->consultation_id,
                'status' => $remote->status,
                'transcript_text' => $remote->transcript_text ?? null,
                'transcript_edited' => $remote->transcript_edited ?? null,
                'transcript_comments' => $remote->transcript_comments ?? null,
                'notes' => $remote->notes ?? null,
                'completed_at' => $remote->completed_at ?? null,
                'edited_at' => $remote->edited_at ?? null,
                'edited_by' => $remote->edited_by ?? null,
                'approved_at' => $remote->approved_at ?? null,
                'approved_by' => $remote->approved_by ?? null,
                'wisebee_created_at' => $remote->created_at ?? null,
            ]
        );
    }
}
