-- name: CreateClient :exec
INSERT INTO clients (clientId, name) VALUES ($1, $2);

-- name: GetClient :one
SELECT * FROM fullClients WHERE clientId = $1;

-- name: ListClients :many
-- Returns all clients ordered by name
SELECT * FROM fullClients ORDER BY name;

-- name: UpdateClient :exec
UPDATE clients SET name = $1 WHERE clientId = $2;

-- name: AddClientCanSync :exec
INSERT INTO clientCanSync (canSync, clientId) VALUES ($1, $2);

-- name: IsClientSynced :one
-- Text extraction has been removed. A client is considered synced when
-- all documents have completed cleaning (clean entry exists OR clean failed).
-- See remove_texttract_and_mocks_plan.md for details.
WITH
docs AS (
    -- Get all documents for this client
    SELECT id, clientId FROM documents WHERE clientId = $1
),
doc_clean_entries as (
    -- Documents with their current clean entries
    SELECT
        d.id AS document_id,
        d.clientId as client_id,
        cte.id AS clean_entry_id,
        cte.fail as clean_fail
    FROM
        docs d
        LEFT JOIN currentCleanEntries cte ON cte.documentId = d.id
)
SELECT (
    -- No documents means client is synced
    NOT EXISTS (SELECT 1 FROM docs)

    OR

    -- All documents have completed processing (clean entry exists OR clean failed)
    NOT EXISTS (
        SELECT 1 FROM doc_clean_entries
        WHERE clean_entry_id IS NULL
    )
)::bool as is_synced;
