-- name: InsertUser :one
INSERT INTO users (email, password_hash)
VALUES ($1, $2)
RETURNING id, email, password_hash, created_at, updated_at;

-- name: InsertSocialUser :one
INSERT INTO users (email, password_hash)
VALUES ($1, NULL)
RETURNING id, email, password_hash, created_at, updated_at;

-- name: GetUserByEmail :one
SELECT id, email, password_hash, created_at, updated_at
FROM users
WHERE email = $1;

-- name: GetUserByID :one
SELECT id, email, password_hash, created_at, updated_at
FROM users
WHERE id = $1;

-- name: IsSocialOnlyUserByEmail :one
SELECT EXISTS (
    SELECT 1
    FROM users
    WHERE email = $1
      AND password_hash IS NULL
)::boolean;

-- name: UpdateUserEmailIfAvailable :one
UPDATE users AS u
SET email = $2,
    updated_at = now()
WHERE u.id = $1
  AND NOT EXISTS (
    SELECT 1 FROM users AS u2 WHERE u2.email = $2 AND u2.id <> u.id
  )
RETURNING u.id, u.email, u.password_hash, u.created_at, u.updated_at;
