-- name: CreateWorkspace :one
INSERT INTO workspaces (
  id, project_id, slug, name, description,
  git_remote_url, default_branch, main_path, sync_status
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)
RETURNING *;

-- name: GetWorkspaceByID :one
SELECT * FROM workspaces WHERE id = $1;

-- name: GetWorkspaceBySlug :one
SELECT w.* FROM workspaces w
JOIN projects p ON p.id = w.project_id
WHERE p.slug = $1 AND w.slug = $2;

-- name: ListWorkspacesByProject :many
SELECT * FROM workspaces WHERE project_id = $1
ORDER BY created_at DESC;

-- name: UpdateWorkspaceCore :one
UPDATE workspaces
SET name = $2, description = $3, default_branch = $4, updated_at = now()
WHERE id = $1
RETURNING *;

-- name: UpdateWorkspaceSyncStatus :one
UPDATE workspaces
SET sync_status = $2,
    last_synced_at = $3,
    last_sync_error = $4,
    updated_at = now()
WHERE id = $1
RETURNING *;

-- name: DeleteWorkspace :exec
DELETE FROM workspaces WHERE id = $1;

-- name: ResetStuckSyncStatuses :many
UPDATE workspaces
SET sync_status = 'error',
    last_sync_error = 'process_restarted_during_' || sync_status,
    updated_at = now()
WHERE sync_status IN ('cloning', 'syncing')
RETURNING id, last_sync_error;

-- name: ListFetchTargets :many
SELECT w.id, p.owner_id, w.name, w.main_path
  FROM workspaces w
  JOIN projects p ON p.id = w.project_id
 WHERE w.archived_at IS NULL
   AND w.sync_status IN ('idle','error')
 ORDER BY w.id;

-- name: MarkSyncingCAS :execrows
UPDATE workspaces SET sync_status='syncing', updated_at=now()
 WHERE id=$1 AND sync_status IN ('idle','error');

-- name: MarkFetchResult :exec
UPDATE workspaces
   SET sync_status = CASE WHEN $2::bool THEN 'idle' ELSE 'error' END,
       last_synced_at = CASE WHEN $2::bool THEN now() ELSE last_synced_at END,
       last_sync_error = $3,
       updated_at = now()
 WHERE id = $1;
