-- name: ListInventory :many
SELECT * FROM "Inventory"
ORDER BY "Name";

-- name: GetReportInventory :many
SELECT * FROM "Inventory"
ORDER BY "CreationTime";

-- name: GetInventoryByName :many
SELECT * FROM "Inventory"
WHERE "Name" = ?;

-- name: GetInventoryVmId :one
SELECT * FROM "Inventory"
WHERE "VmId" = sqlc.arg('vmId')  AND "Datacenter" = sqlc.arg('datacenterName');

-- name: GetInventoryEventId :one
SELECT * FROM "Inventory"
WHERE "CloudId" = ? LIMIT 1;

-- name: CreateInventory :one
INSERT INTO "Inventory" (
    "Name", "Vcenter", "VmId", "EventKey", "CloudId", "CreationTime", "ResourcePool", "VmType", "IsTemplate", "Datacenter", "Cluster", "Folder", "ProvisionedDisk", "InitialVcpus", "InitialRam", "SrmPlaceholder", "PoweredOn"
) VALUES(
    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)
RETURNING *;

-- name: InventoryMarkDeleted :exec
UPDATE "Inventory"
SET "DeletionTime" = sqlc.arg('deletionTime')
WHERE "VmId" = sqlc.arg('vmId') AND "Datacenter" = sqlc.arg('datacenterName');

-- name: InventoryCleanup :exec
DELETE FROM "Inventory"
WHERE "VmId" = sqlc.arg('vmId') AND "Datacenter" = sqlc.arg('datacenterName')
RETURNING *;

-- name: CreateUpdate :one
INSERT INTO "Updates" (
    "InventoryId", "EventKey", "EventId", "UpdateTime", "UpdateType", "NewVcpus", "NewRam", "NewResourcePool", "NewProvisionedDisk", "UserName"
) VALUES(
    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)
RETURNING *;

-- name: CleanupUpdates :exec
DELETE FROM "Updates"
WHERE "UpdateType" = sqlc.arg('updateType') AND "UpdateTime" <= sqlc.arg('updateTime')
RETURNING *;

-- name: CreateEvent :one
INSERT INTO "Events" (
    "CloudId", "Source", "EventTime", "ChainId", "VmId", "VmName", "EventType", "EventKey", "DatacenterId", "DatacenterName", "ComputeResourceId", "ComputeResourceName", "UserName"
) VALUES(
    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)
RETURNING *;

-- name: ListEvents :many
SELECT * FROM "Events"
ORDER BY "EventTime";

-- name: ListUnprocessedEvents :many
SELECT * FROM "Events"
WHERE "Processed" = 0
AND "EventTime" > sqlc.arg('eventTime')
ORDER BY "EventTime";

-- name: UpdateEventsProcessed :exec
UPDATE "Events"
SET "Processed" = 1
WHERE "Eid" = sqlc.arg('eid');