-- name: CreateWorkspace :one
-- The name is what people see and the only thing the create form asks for;
-- uq_workspaces_org_id_name_ci keeps it unambiguous within the organization
-- among live workspaces. `key` is the optional declarative address
-- (entity-keys §3), unique within the organization rather than globally
-- because a workspace is a child; UI-created workspaces leave it NULL, and a
-- singleton workspace is addressed through its organization.
INSERT INTO core.workspaces (org_id, name, key)
VALUES ($1, $2, sqlc.narg(key))
RETURNING *;

-- name: GetWorkspaceByOrgAndKey :one
-- Child key resolver (entity-keys §5): the declarative address of a
-- workspace is its organization's key plus its own, never a name.
-- uq_workspaces_org_id_key guarantees at most one row matches.
SELECT * FROM core.workspaces
WHERE org_id = $1 AND key = $2;

-- 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 its name
-- within the organization (entity-keys). The conflict target
-- repeats the predicate of the partial index uq_workspaces_org_id_name_ci
-- so Postgres can infer it. Only called when the system org has no
-- workspace yet.
INSERT INTO core.workspaces (org_id, name)
VALUES ($1, $2)
ON CONFLICT (org_id, lower(name)) WHERE status <> 'deleted' 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 name) 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;
