-- 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: UpsertAdmin :one
INSERT INTO users (email, password_hash, name, is_admin)
VALUES ($1, $2, $3, true)
ON CONFLICT (email) DO UPDATE SET password_hash = EXCLUDED.password_hash, name = EXCLUDED.name, is_admin = true
RETURNING *;

-- name: InsertScan :one
INSERT INTO scans (tag_id, lat, lng, location_shared, scanner_phone, fingerprint, ip)
VALUES ($1, $2, $3, $4, $5, $6, $7)
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, fingerprint = $3 WHERE id = $1;

-- name: GetRecentScanByFingerprint :one
SELECT * FROM scans
WHERE fingerprint = $1 AND id <> $2 AND scanned_at > now() - interval '24 hours'
ORDER BY scanned_at DESC
LIMIT 1;

-- name: GetOrderByID :one
SELECT * FROM orders WHERE id = $1;

-- name: CountAlertsByTagSince :one
SELECT count(*) FROM scans
WHERE tag_id = $1 AND alert_sent = TRUE AND scanned_at > $2;

-- name: CountAlertsByIPSince :one
SELECT count(*) FROM scans
WHERE ip = $1 AND alert_sent = TRUE AND scanned_at > $2;

-- name: AddSmsUsed :exec
UPDATE tags SET sms_used = sms_used + 1, updated_at = now() WHERE id = $1;

-- name: InsertShortCode :one
INSERT INTO url_shortened (code, scan_id) VALUES ($1, $2) RETURNING *;

-- name: GetShortCode :one
SELECT * FROM url_shortened WHERE code = $1;

-- name: GetScanByID :one
SELECT * FROM scans WHERE id = $1;
