<?php

namespace App\Models;

/** See CreateAiMessageDraftsTable's migration comment. */
class AiMessageDraftModel extends TenantModel
{
    protected $table            = 'ai_message_drafts';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useTimestamps    = true;
    protected $createdField     = 'created_at';
    protected $updatedField     = '';

    protected $allowedFields = [
        'category',
        'guest_id',
        'booking_id',
        'to_phone',
        'draft_text',
        'status',
        'data_snapshot',
        'sent_at',
        'sent_by',
    ];

    public function pending(?string $category = null): array
    {
        $builder = $this->select('ai_message_drafts.*, guests.full_name as guest_name')
            ->join('guests', 'guests.id = ai_message_drafts.guest_id', 'left')
            ->where('ai_message_drafts.status', 'pending');

        if ($category !== null) {
            $builder->where('ai_message_drafts.category', $category);
        }

        return $builder->orderBy('ai_message_drafts.created_at', 'desc')->findAll();
    }

    public function countPending(): int
    {
        return $this->where('status', 'pending')->countAllResults();
    }
}
