<?php
/**
 * FreshCloud Mail — start a new compose draft
 * POST /api/email/compose/start
 * Body: { user_id, account_id, mode, reply_to_msg_id?, forward_of_msg_id? }
 */

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

$body = json_decode(file_get_contents('php://input') ?: '{}', true) ?: [];
$userId = $body['user_id'] ?? null;
$accountId = $body['account_id'] ?? null;
$mode = $body['mode'] ?? null;

if (!$userId || !$accountId || !$mode) {
    freshcloud_mail_error(400, 'missing_required_field', 'user_id, account_id, and mode are required');
}

if (!in_array($mode, ['new', 'reply', 'reply-all', 'forward'], true)) {
    freshcloud_mail_error(400, 'invalid_mode', "mode must be one of: new, reply, reply-all, forward (got: $mode)");
}

// Try real Composer first
$composer = freshcloud_mail_composer($userId, $accountId);
if ($composer !== null) {
    try {
        $draftId = $composer->start(
            $userId,
            $accountId,
            $mode,
            $body['reply_to_msg_id'] ?? null,
            $body['forward_of_msg_id'] ?? null
        );
        freshcloud_mail_json(200, [
            'status' => 'draft_created',
            'draft_id' => $draftId,
            'user_id' => $userId,
            'account_id' => $accountId,
            'mode' => $mode,
            'timestamp' => gmdate('c'),
        ]);
    } catch (\Throwable $e) {
        freshcloud_mail_error(500, 'composer_failed', $e->getMessage());
    }
}

// v0.1.0-test: engine not wired, return a stub draft_id
freshcloud_mail_json(200, [
    'status' => 'draft_created',
    'draft_id' => 'draft_' . bin2hex(random_bytes(8)),
    'user_id' => $userId,
    'account_id' => $accountId,
    'mode' => $mode,
    'note' => 'v0.1.0-test stub — engine adapters not yet wired. Returns fake draft_id.',
    'timestamp' => gmdate('c'),
]);
