-- name: CreateActivityLog :one
INSERT INTO activity_logs (
    actor_id, actor_role, action, resource_type, resource_id,
    message, metadata, ip_address, user_agent
) VALUES (
    sqlc.narg('actor_id'), sqlc.narg('actor_role'),
    @action, @resource_type, sqlc.narg('resource_id'),
    sqlc.narg('message'), COALESCE(sqlc.narg('metadata'), '{}'::jsonb),
    sqlc.narg('ip_address'), sqlc.narg('user_agent')
)
RETURNING *;

-- name: ListActivityLogs :many
SELECT
    COUNT(*) OVER() AS total_count,
    al.id,
    al.actor_id,
    al.actor_role,
    al.action,
    al.resource_type,
    al.resource_id,
    al.message,
    al.metadata,
    al.ip_address,
    al.user_agent,
    al.created_at
FROM activity_logs al
WHERE
    (sqlc.narg('filter_actor_id')::bigint IS NULL OR al.actor_id = sqlc.narg('filter_actor_id'))
    AND (sqlc.narg('filter_action')::text IS NULL OR al.action = sqlc.narg('filter_action'))
    AND (sqlc.narg('filter_resource_type')::text IS NULL OR al.resource_type = sqlc.narg('filter_resource_type'))
    AND (sqlc.narg('filter_resource_id')::bigint IS NULL OR al.resource_id = sqlc.narg('filter_resource_id'))
    AND (sqlc.narg('filter_after')::timestamptz IS NULL OR al.created_at >= sqlc.narg('filter_after'))
    AND (sqlc.narg('filter_before')::timestamptz IS NULL OR al.created_at <= sqlc.narg('filter_before'))
ORDER BY al.created_at DESC
LIMIT @log_limit OFFSET @log_offset;

-- name: GetActivityLogByID :one
SELECT * FROM activity_logs WHERE id = $1;
