./.github/workflows/deploy-frontend.yml

name: Deploy Frontend (knowledge-base)

on:
  push:
    branches: [main]
    paths:
      - "knowledge-base/frontend/**"
  workflow_dispatch:
    inputs:
      reason:
        description: "手動デプロイの理由"
        required: false
        default: "手動実行"

permissions:
  id-token: write # OIDC トークン取得に必要
  contents: read

jobs:
  deploy:
    name: Frontend Build & S3 Deploy
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: "18"
          cache: "npm"
          cache-dependency-path: knowledge-base/frontend/package.json

      - name: Configure AWS credentials (OIDC)
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::903877990773:role/github-actions-knowledge-base
          aws-region: ap-northeast-1
          role-session-name: GitHubActions-FrontendDeploy-${{ github.run_id }}

      - name: Verify AWS identity
        run: aws sts get-caller-identity

      - name: Install dependencies
        working-directory: knowledge-base/frontend
        run: npm ci

      - name: Build (production)
        working-directory: knowledge-base/frontend
        run: npm run build
        # .env.production が使われる(VITE_OKTA_ISSUER, VITE_OKTA_CLIENT_ID 含む)
        # VITE_API_GATEWAY_URL / VITE_ASSIST_URL は空欄 → CloudFront 相対パスルーティング

      - name: Sync to S3
        run: |
          # キャッシュ可能な静的アセットを先に更新(長期キャッシュ)
          aws s3 sync knowledge-base/frontend/dist s3://historical-research-web \
            --delete \
            --cache-control "public, max-age=31536000, immutable" \
            --exclude "index.html"

          # index.html は毎回再検証させる(no-cache)
          aws s3 cp knowledge-base/frontend/dist/index.html \
            s3://historical-research-web/index.html \
            --cache-control "no-cache, no-store, must-revalidate"

      - name: Invalidate CloudFront cache
        run: |
          aws cloudfront create-invalidation \
            --distribution-id E2BIKMVFQ3WW5S \
            --paths "/*"

      - name: Done
        run: echo "Frontend deployed to s3://historical-research-web and CloudFront cache invalidated."