-- name: CreateWorkspace :one
INSERT INTO core.workspaces (org_id, name, slug)
VALUES ($1, $2, $3)
RETURNING *;

-- name: GetWorkspacesByOrgID :many
SELECT * FROM core.workspaces
WHERE org_id = $1
ORDER BY name;

-- name: GetWorkspaceByID :one
SELECT * FROM core.workspaces
WHERE workspace_id = $1;

-- name: CountWorkspacesByOrgID :one
SELECT COUNT(*) FROM core.workspaces
WHERE org_id = $1;

-- name: EnsureSystemWorkspace :exec
-- Idempotently insert the System tenant's workspace (keyed on the unique
-- org_id+slug). Only called when the system org has no workspace yet.
INSERT INTO core.workspaces (org_id, name, slug)
VALUES ($1, $2, $3)
ON CONFLICT (org_id, slug) DO NOTHING;

-- name: GetSystemOrgWorkspace :one
-- Natural-key resolver: the workspace of the singleton organization whose
-- org_type is 'system'. Returns the oldest workspace so a pre-existing
-- workspace (e.g. an ad-hoc seed using a different slug) is adopted rather
-- than duplicated.
SELECT w.* FROM core.workspaces w
JOIN core.organizations o ON o.org_id = w.org_id
WHERE o.org_type = 'system'
ORDER BY w.created_at
LIMIT 1;
