-- name: CountArticlesByTenant :one
SELECT COUNT(*) FROM articles
WHERE tenant_id = sqlc.arg(tenant_id) AND deleted_at IS NULL;

-- name: CountPublishedArticlesByTenant :one
SELECT COUNT(*) FROM articles
WHERE tenant_id = sqlc.arg(tenant_id) AND publish_status = 'success' AND deleted_at IS NULL;

-- name: CountBrandsByTenant :one
SELECT COUNT(*) FROM brands
WHERE tenant_id = sqlc.arg(tenant_id) AND deleted_at IS NULL;

-- name: GetRecentArticles :many
SELECT a.id, a.generate_status, a.publish_status, a.source_type, a.created_at,
       av.title, av.markdown_content, av.word_count, av.source_label,
       t.template_name,
       COALESCE(
         NULLIF(gt.input_params_json ->> 'generation_mode', ''),
         CASE WHEN a.source_type = 'custom_generation' THEN 'instant'::TEXT ELSE NULL::TEXT END
       ) AS generation_mode
FROM articles a
LEFT JOIN article_versions av ON av.id = a.current_version_id
LEFT JOIN article_templates t ON t.id = a.template_id
LEFT JOIN LATERAL (
    SELECT input_params_json
    FROM generation_tasks
    WHERE article_id = a.id
    ORDER BY created_at DESC
    LIMIT 1
) gt ON true
WHERE a.tenant_id = sqlc.arg(tenant_id) AND a.deleted_at IS NULL
ORDER BY a.created_at DESC
LIMIT 10;

-- name: GetQuotaSummary :one
SELECT COALESCE(
    (SELECT balance_after FROM tenant_quota_ledgers
     WHERE tenant_id = sqlc.arg(tenant_id) AND quota_type = 'article_generation'
     ORDER BY created_at DESC LIMIT 1), 0
)::INT AS balance;

-- name: GetActivePlanForTenant :one
SELECT p.plan_code, p.name AS plan_name, p.quota_policy_json,
       s.start_at, s.end_at
FROM tenant_plan_subscriptions s
JOIN plans p ON p.id = s.plan_id
WHERE s.tenant_id = sqlc.arg(tenant_id) AND s.status = 'active' AND s.deleted_at IS NULL
LIMIT 1;
