-- name: CreateUser :one
INSERT INTO users (email, password_hash, name, phone)
VALUES ($1, $2, $3, $4)
RETURNING *;

-- name: GetUserByEmail :one
SELECT * FROM users WHERE email = $1;

-- name: GetUserByID :one
SELECT * FROM users WHERE id = $1;

-- name: ListTagsByOwner :many
SELECT * FROM tags WHERE owner_id = $1 ORDER BY created_at DESC;

-- name: GetTagByCode :one
SELECT * FROM tags WHERE tag_code = $1;

-- name: GetTagByID :one
SELECT * FROM tags WHERE id = $1;

-- name: CountTagsByOwner :one
SELECT count(*) FROM tags WHERE owner_id = $1;

-- name: BindTag :one
UPDATE tags
SET owner_id = $1, updated_at = now()
WHERE tag_code = $2 AND owner_id IS NULL AND status = 'unset'
RETURNING *;

-- name: UpdateTagDetails :one
UPDATE tags
SET item_type=$2, description=$3, photo_url=$4, phone=$5, address=$6, notes=$7, sms_enabled=$8, status='active', updated_at=now()
WHERE id=$1
RETURNING *;

-- name: ClearTagOwner :one
UPDATE tags
SET owner_id=NULL, status='unset', item_type=NULL, description=NULL, photo_url=NULL, phone=NULL, address=NULL, notes=NULL, updated_at=now()
WHERE id=$1
RETURNING *;

-- name: SetTagStatus :exec
UPDATE tags SET status=$2, updated_at=now() WHERE id=$1;

-- name: InsertTag :one
INSERT INTO tags (tag_code) VALUES ($1)
RETURNING *;

-- name: InsertScan :one
INSERT INTO scans (tag_id, lat, lng, location_shared, scanner_phone)
VALUES ($1, $2, $3, $4, $5)
RETURNING *;

-- name: GetLastAlertByTag :one
SELECT * FROM scans
WHERE tag_id = $1 AND alert_sent = TRUE
ORDER BY scanned_at DESC
LIMIT 1;

-- name: GetLatestScanByTag :one
SELECT * FROM scans
WHERE tag_id = $1
ORDER BY scanned_at DESC
LIMIT 1;

-- name: SetScanAlertSent :exec
UPDATE scans SET alert_sent = $2 WHERE id = $1;

-- name: SetScanPhone :exec
UPDATE scans SET scanner_phone = $2 WHERE id = $1;
