-- name: GetUserByEmail :one
SELECT id, email, phone, password_hash, name, avatar_url, status, created_at, updated_at
FROM users
WHERE email = sqlc.arg(email) AND deleted_at IS NULL;

-- name: GetUserByLoginIdentifier :one
SELECT id, email, phone, password_hash, name, avatar_url, status, created_at, updated_at
FROM users
WHERE (email = sqlc.arg(login_identifier) OR phone = sqlc.arg(login_identifier))
  AND deleted_at IS NULL;

-- name: GetUserByID :one
SELECT id, email, phone, password_hash, name, avatar_url, status, created_at, updated_at
FROM users
WHERE id = sqlc.arg(id) AND deleted_at IS NULL;

-- name: GetTenantMembership :one
SELECT tm.id,
       tm.tenant_id,
       tm.user_id,
       tm.tenant_role,
       tm.created_at,
       wm.workspace_id AS primary_workspace_id
FROM tenant_memberships tm
JOIN workspace_memberships wm
  ON wm.tenant_id = tm.tenant_id
 AND wm.user_id = tm.user_id
 AND wm.is_primary = TRUE
WHERE tm.user_id = sqlc.arg(user_id) AND tm.deleted_at IS NULL
LIMIT 1;

-- name: GetTenantMembershipByTenantAndUser :one
SELECT tm.id,
       tm.tenant_id,
       tm.user_id,
       tm.tenant_role,
       tm.created_at,
       wm.workspace_id AS primary_workspace_id
FROM tenant_memberships tm
JOIN workspace_memberships wm
  ON wm.tenant_id = tm.tenant_id
 AND wm.user_id = tm.user_id
 AND wm.is_primary = TRUE
WHERE tm.tenant_id = sqlc.arg(tenant_id) AND tm.user_id = sqlc.arg(user_id) AND tm.deleted_at IS NULL;
