export const DEFAULT_SUPERBLOCKS_DOMAIN = 'app.superblocks.com';

export function isGitHubRemoteUrl(remoteUrl: string): boolean {
  return /(^git@github\.com:)|(^https?:\/\/github\.com\/)|(^ssh:\/\/git@github\.com\/)/.test(remoteUrl.trim());
}

export function buildGithubSuperblocksSyncWorkflow(domain: string = DEFAULT_SUPERBLOCKS_DOMAIN): string {
  return `name: Sync changes to Superblocks

on:
  push:
    branches:
      - main
  workflow_dispatch:

jobs:
  superblocks-sync:
    runs-on: ubuntu-latest
    name: Sync to Superblocks
    permissions:
      contents: read
      packages: read
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          persist-credentials: false

      # Optional: needed only if the CLI version is private in GitHub Packages.
      - name: Setup npm credentials
        env:
          NPM_AUTH_TOKEN: \${{ secrets.NPM_AUTH_TOKEN }}
        run: |
          if [ -n "$NPM_AUTH_TOKEN" ]; then
            echo "@superblocksteam:registry=https://npm.pkg.github.com" >> .npmrc
            echo "always-auth=true" >> .npmrc
            echo "//npm.pkg.github.com/:_authToken=$NPM_AUTH_TOKEN" >> .npmrc
          fi

      - name: Sync
        uses: superblocksteam/sync-action@v1
        env:
          NPM_CONFIG_USERCONFIG: \${{ github.workspace }}/.npmrc
        with:
          token: \${{ secrets.SUPERBLOCKS_TOKEN }}
          domain: ${domain}
          path: .
          sha: \${{ github.sha }}
`;
}

export function getSuperblocksDomainFromBaseUrl(superblocksBaseUrl: string): string {
  const trimmed = superblocksBaseUrl.trim();
  if (!trimmed) {
    return DEFAULT_SUPERBLOCKS_DOMAIN;
  }

  try {
    return new URL(trimmed).host || DEFAULT_SUPERBLOCKS_DOMAIN;
  } catch {
    return DEFAULT_SUPERBLOCKS_DOMAIN;
  }
}

export function buildGithubSuperblocksSyncWorkflowFromBaseUrl(superblocksBaseUrl: string): string {
  return buildGithubSuperblocksSyncWorkflow(getSuperblocksDomainFromBaseUrl(superblocksBaseUrl));
}
