<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\BaseModel;

final class EmailMessageModel extends BaseModel
{
    protected string $table = 'email_messages';
    protected array $fillable = [
        'email_account_id', 'direction', 'related_lead_id', 'related_customer_id',
        'from_address', 'to_address', 'subject', 'body_html', 'status', 'sent_at',
    ];
    protected bool $timestamps = false;
    protected bool $softDeletes = true;
    protected bool $auditStamps = false;

    public function forEntity(string $entityType, int $entityId): array
    {
        $column = $entityType === 'customer' ? 'related_customer_id' : 'related_lead_id';

        $stmt = $this->db->prepare(
            "SELECT * FROM email_messages WHERE {$column} = :id AND deleted_at IS NULL ORDER BY created_at DESC"
        );
        $stmt->execute(['id' => $entityId]);

        return $stmt->fetchAll();
    }

    public function recentSent(int $limit = 50): array
    {
        $stmt = $this->db->prepare(
            "SELECT * FROM email_messages WHERE direction = 'outbound' AND deleted_at IS NULL ORDER BY created_at DESC LIMIT :limit"
        );
        $stmt->bindValue('limit', $limit, \PDO::PARAM_INT);
        $stmt->execute();

        return $stmt->fetchAll();
    }
}
