-- name: ListImageAssets :many
SELECT id, tenant_id, folder_id, object_key, name, size_bytes, status, created_by, created_at, updated_at
FROM image_assets
WHERE tenant_id = sqlc.arg(tenant_id)
  AND status = 'active'
  AND deleted_at IS NULL
  AND (
    sqlc.narg(folder_id)::BIGINT IS NULL
    OR (sqlc.narg(folder_id)::BIGINT = 0 AND folder_id IS NULL)
    OR folder_id = sqlc.narg(folder_id)::BIGINT
  )
  AND (sqlc.narg(search_query)::TEXT IS NULL OR name ILIKE '%' || sqlc.narg(search_query)::TEXT || '%')
ORDER BY created_at DESC
LIMIT sqlc.arg(page_size) OFFSET sqlc.arg(page_offset);

-- name: CountImageAssets :one
SELECT COUNT(*)::INT AS total
FROM image_assets
WHERE tenant_id = sqlc.arg(tenant_id)
  AND status = 'active'
  AND deleted_at IS NULL
  AND (
    sqlc.narg(folder_id)::BIGINT IS NULL
    OR (sqlc.narg(folder_id)::BIGINT = 0 AND folder_id IS NULL)
    OR folder_id = sqlc.narg(folder_id)::BIGINT
  )
  AND (sqlc.narg(search_query)::TEXT IS NULL OR name ILIKE '%' || sqlc.narg(search_query)::TEXT || '%');

-- name: GetImageAsset :one
SELECT id, tenant_id, folder_id, object_key, name, size_bytes, status, created_by, created_at, updated_at
FROM image_assets
WHERE id = sqlc.arg(id) AND tenant_id = sqlc.arg(tenant_id);

-- name: InsertImageAsset :one
INSERT INTO image_assets (tenant_id, folder_id, object_key, name, size_bytes, status, created_by)
VALUES (sqlc.arg(tenant_id), sqlc.narg(folder_id), sqlc.arg(object_key), sqlc.arg(name), sqlc.arg(size_bytes), sqlc.arg(status), sqlc.arg(created_by))
RETURNING id;

-- name: UpdateImageAssetStatus :exec
UPDATE image_assets
SET status = sqlc.arg(status), updated_at = NOW()
WHERE id = sqlc.arg(id) AND tenant_id = sqlc.arg(tenant_id);

-- name: UpdateImageAssetDeleted :exec
UPDATE image_assets
SET status = 'deleted', deleted_at = NOW(), updated_at = NOW()
WHERE id = sqlc.arg(id) AND tenant_id = sqlc.arg(tenant_id);

-- name: UpdateImageAssetName :exec
UPDATE image_assets
SET name = sqlc.arg(name), updated_at = NOW()
WHERE id = sqlc.arg(id) AND tenant_id = sqlc.arg(tenant_id);

-- name: UpdateImageAssetFolder :exec
UPDATE image_assets
SET folder_id = sqlc.narg(folder_id), updated_at = NOW()
WHERE id = sqlc.arg(id) AND tenant_id = sqlc.arg(tenant_id);

-- name: ListActiveImagesByFolder :many
SELECT id, object_key, size_bytes
FROM image_assets
WHERE tenant_id = sqlc.arg(tenant_id)
  AND folder_id = sqlc.arg(folder_id)
  AND status = 'active'
  AND deleted_at IS NULL;

-- name: MarkImagesInFolderPendingDelete :exec
UPDATE image_assets
SET status = 'pending_delete', folder_id = NULL, updated_at = NOW()
WHERE tenant_id = sqlc.arg(tenant_id)
  AND folder_id = sqlc.arg(folder_id)
  AND status = 'active'
  AND deleted_at IS NULL;

-- name: CountUncategorizedImages :one
SELECT COUNT(*)::INT AS count
FROM image_assets
WHERE tenant_id = sqlc.arg(tenant_id)
  AND folder_id IS NULL
  AND status = 'active'
  AND deleted_at IS NULL;
