// engine/deploy/providers/railway.ts — SPEC-478: Railway deploy via GraphQL API
// SPEC-597-EXEMPT: provider-specific implementation; the literal 'railway'
// IS the canonical id for this module.
const RAILWAY_GRAPHQL_URL = 'https://backboard.railway.app/graphql/v2';
/** Trigger a Railway deployment via GraphQL serviceInstanceDeploy mutation. */
export async function deployToRailway(config, _options) {
    // config.projectId is the Railway service_id, config.team is the environment_id
    const serviceId = config.projectId ?? '';
    const environmentId = config.team ?? '';
    const mutation = `
    mutation DeployService($serviceId: String!, $environmentId: String!) {
      serviceInstanceDeploy(serviceId: $serviceId, environmentId: $environmentId)
    }
  `;
    try {
        const response = await fetch(RAILWAY_GRAPHQL_URL, {
            method: 'POST',
            headers: {
                Authorization: `Bearer ${config.token}`,
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                query: mutation,
                variables: { serviceId, environmentId },
            }),
        });
        if (!response.ok) {
            const text = await response.text();
            return {
                id: `railway-error-${String(Date.now())}`,
                provider: 'railway',
                status: 'error',
                createdAt: new Date().toISOString(),
                errorMessage: `Railway API ${String(response.status)}: ${text.slice(0, 200)}`,
            };
        }
        const body = (await response.json());
        if (body.errors && body.errors.length > 0) {
            const msg = body.errors.map((e) => e.message).join('; ');
            return {
                id: `railway-error-${String(Date.now())}`,
                provider: 'railway',
                status: 'error',
                createdAt: new Date().toISOString(),
                errorMessage: `Railway GraphQL error: ${msg}`,
            };
        }
        const deploymentId = body.data?.serviceInstanceDeploy ?? `railway-${String(Date.now())}`;
        return {
            id: deploymentId,
            provider: 'railway',
            status: 'building',
            createdAt: new Date().toISOString(),
        };
    }
    catch (err) {
        return {
            id: `railway-error-${String(Date.now())}`,
            provider: 'railway',
            status: 'error',
            createdAt: new Date().toISOString(),
            errorMessage: err instanceof Error ? err.message : String(err),
        };
    }
}
/** Check the status of a Railway deployment via GraphQL query. */
export async function getRailwayDeploymentStatus(config, deploymentId) {
    const query = `
    query GetDeployment($id: String!) {
      deployment(id: $id) {
        id
        status
        url
      }
    }
  `;
    try {
        const response = await fetch(RAILWAY_GRAPHQL_URL, {
            method: 'POST',
            headers: {
                Authorization: `Bearer ${config.token}`,
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ query, variables: { id: deploymentId } }),
        });
        if (!response.ok) {
            return {
                id: deploymentId,
                provider: 'railway',
                status: 'error',
                createdAt: new Date().toISOString(),
                errorMessage: `Railway API ${String(response.status)}`,
            };
        }
        const body = (await response.json());
        if (body.errors && body.errors.length > 0) {
            const msg = body.errors.map((e) => e.message).join('; ');
            return {
                id: deploymentId,
                provider: 'railway',
                status: 'error',
                createdAt: new Date().toISOString(),
                errorMessage: `Railway GraphQL error: ${msg}`,
            };
        }
        const dep = body.data?.deployment;
        if (!dep) {
            return {
                id: deploymentId,
                provider: 'railway',
                status: 'error',
                createdAt: new Date().toISOString(),
                errorMessage: 'Railway deployment not found',
            };
        }
        return {
            id: dep.id,
            provider: 'railway',
            url: dep.url,
            status: mapRailwayState(dep.status ?? ''),
            createdAt: new Date().toISOString(),
        };
    }
    catch (err) {
        return {
            id: deploymentId,
            provider: 'railway',
            status: 'error',
            createdAt: new Date().toISOString(),
            errorMessage: err instanceof Error ? err.message : String(err),
        };
    }
}
function mapRailwayState(state) {
    switch (state.toUpperCase()) {
        case 'SUCCESS':
            return 'ready';
        case 'BUILDING':
        case 'DEPLOYING':
        case 'QUEUED':
            return 'building';
        case 'FAILED':
            return 'error';
        default:
            return 'pending';
    }
}
//# sourceMappingURL=railway.js.map