<?php
require_once __DIR__ . '/../Core.php';

class MailboxSyncEvent extends Model
{
    public function log(array $data): int
    {
        $stmt = $this->db->prepare('INSERT INTO mailbox_sync_events (connected_mailbox_id, event_type, status, summary, detail_json, imported_count, highest_uid, sync_mode, provider) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
        $stmt->execute([
            (int)($data['connected_mailbox_id'] ?? 0) ?: null,
            trim((string)($data['event_type'] ?? 'sync')) ?: 'sync',
            trim((string)($data['status'] ?? 'ok')) ?: 'ok',
            trim((string)($data['summary'] ?? '')) ?: null,
            !empty($data['detail_json']) ? json_encode($data['detail_json'], JSON_UNESCAPED_SLASHES) : null,
            (int)($data['imported_count'] ?? 0),
            (int)($data['highest_uid'] ?? 0),
            trim((string)($data['sync_mode'] ?? '')) ?: null,
            trim((string)($data['provider'] ?? '')) ?: null,
        ]);
        return (int)$this->db->lastInsertId();
    }

    public function recent(int $limit = 30, ?int $mailboxId = null): array
    {
        $sql = 'SELECT mse.*, cm.name AS mailbox_name, cm.email_address
            FROM mailbox_sync_events mse
            LEFT JOIN connected_mailboxes cm ON cm.id = mse.connected_mailbox_id';
        $params = [];
        if ($mailboxId !== null && $mailboxId > 0) {
            $sql .= ' WHERE mse.connected_mailbox_id = ?';
            $params[] = $mailboxId;
        }
        $sql .= ' ORDER BY mse.id DESC LIMIT ?';
        $stmt = $this->db->prepare($sql);
        $i = 1;
        foreach ($params as $param) {
            $stmt->bindValue($i++, $param, PDO::PARAM_INT);
        }
        $stmt->bindValue($i, max(1, $limit), PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }
}
