<?php
/**
 * FreshCloud Mail — send a draft
 * POST /api/email/compose/{id}/send
 * Body: { user_id, account_id, to, cc?, bcc?, subject, body_html?, body_text?, attachment_ids? }
 */

require_once __DIR__ . '/../_bootstrap.php';

$body = json_decode(file_get_contents('php://input') ?: '{}', true) ?: [];

$userId = $body['user_id'] ?? null;
$accountId = $body['account_id'] ?? null;
$to = $body['to'] ?? [];
$subject = $body['subject'] ?? '';
$bodyHtml = $body['body_html'] ?? '';
$bodyText = $body['body_text'] ?? '';

if (!$userId || !$accountId) {
    freshcloud_mail_error(400, 'missing_user_or_account', 'user_id and account_id are required');
}
if (empty($to)) {
    freshcloud_mail_error(400, 'no_recipients', 'at least one recipient in to is required');
}
if (empty(trim($subject))) {
    freshcloud_mail_error(400, 'no_subject', 'subject is required');
}
if (empty(trim($bodyHtml)) && empty(trim($bodyText))) {
    freshcloud_mail_error(400, 'no_body', 'body_html or body_text is required');
}

$composer = freshcloud_mail_composer($userId, $accountId);
if ($composer !== null) {
    try {
        $request = \FreshCloud\Mail\Compose\ComposeRequest::fromArray($body);
        $result = $composer->send($userId, $accountId, $request);
        freshcloud_mail_json(200, [
            'status' => strtolower($result->status->name),
            'message_id' => $result->messageId,
            'sent_at' => $result->sentAt?->format('c'),
            'error' => $result->error,
            'timestamp' => gmdate('c'),
        ]);
    } catch (\Throwable $e) {
        freshcloud_mail_error(500, 'composer_failed', $e->getMessage());
    }
}

// v0.1.0-test: stub response
freshcloud_mail_json(200, [
    'status' => 'sent',
    'message_id' => '<' . bin2hex(random_bytes(8)) . '@freshcloud.local>',
    'sent_at' => gmdate('c'),
    'note' => 'v0.1.0-test stub — Composer::send not yet wired to real SMTP. Validation passed.',
    'timestamp' => gmdate('c'),
]);
