import { REPOSITORY_CLONE_STATES, REPOSITORY_LINK_STATES, REPOSITORY_PROJECTION_PROVIDERS, REPOSITORY_PROJECTION_PUBLIC_SOURCE, REPOSITORY_PROJECTION_STATUSES, readRepositoryCoordinate, readRepositoryLabel, toneForRepositoryStatus, } from "./repositoryProjectionContract.js";
const STATUS_SET = new Set(REPOSITORY_PROJECTION_STATUSES);
const PROVIDER_SET = new Set(REPOSITORY_PROJECTION_PROVIDERS);
const LINK_STATE_SET = new Set(REPOSITORY_LINK_STATES);
const CLONE_STATE_SET = new Set(REPOSITORY_CLONE_STATES);
export class RepositoryProjectionService {
    store;
    constructor(store) {
        this.store = store;
    }
    listForWorkspace(workspaceId) {
        const items = [];
        if (workspaceId) {
            const rows = this.store.listRepositoryBindings(workspaceId);
            for (const row of rows) {
                if (!STATUS_SET.has(row.status))
                    continue;
                const label = readRepositoryLabel(row.displayLabel);
                if (!label)
                    continue;
                const status = row.status;
                const provider = PROVIDER_SET.has(row.provider)
                    ? row.provider
                    : "unknown";
                const linkState = LINK_STATE_SET.has(row.linkState)
                    ? row.linkState
                    : "unlinked";
                const cloneState = CLONE_STATE_SET.has(row.cloneState)
                    ? row.cloneState
                    : "idle";
                items.push({
                    source: REPOSITORY_PROJECTION_PUBLIC_SOURCE,
                    id: row.id,
                    workspaceId: row.workspaceId,
                    displayLabel: label,
                    providerLabel: provider,
                    status,
                    tone: toneForRepositoryStatus(status),
                    lastSyncLabel: readRepositoryLabel(row.lastSyncLabel ?? null),
                    lastErrorCode: readRepositoryLabel(row.lastErrorCode ?? null),
                    owner: readRepositoryCoordinate(row.owner ?? null),
                    repo: readRepositoryCoordinate(row.repo ?? null),
                    defaultBranch: readRepositoryCoordinate(row.defaultBranch ?? null),
                    linkState,
                    cloneState,
                    // Boolean only — the absolute path itself is never projected.
                    hasLocalWorkingCopy: typeof row.localPath === "string" && row.localPath.length > 0,
                });
            }
        }
        return {
            contractVersion: "v1",
            generatedAt: new Date().toISOString(),
            items,
        };
    }
}
