/**
 * Welcome to Cloudflare Workers! This is your first worker.
 *
 * - Run "npm run dev" in your terminal to start a development server
 * - Open a browser tab at http://localhost:8787/ to see your worker in action
 * - Run "npm run deploy" to publish your worker
 *
 * Learn more at https://developers.cloudflare.com/workers/
 */

export default {
  async fetch(request, env, _ctx) {
    const ctx = {
      cfg: {
        serviceDid: "did:web:test-feed1.sound-cr.workers.dev",
        hostname: "test-feed1.sound-cr.workers.dev",
      },
    };

    // `https://test-feed1.sound-cr.workers.dev/.well-known/did.json` にアクセスしたとき用にJSONを返す
    if (request.url.endsWith("/.well-known/did.json")) {
      if (!ctx.cfg.serviceDid.endsWith(ctx.cfg.hostname)) {
        return new Response(undefined, { status: 404 });
      }
      return Response.json({
        "@context": ["https://www.w3.org/ns/did/v1"],
        id: ctx.cfg.serviceDid,
        service: [
          {
            id: "#bsky_fg",
            type: "BskyFeedGenerator",
            serviceEndpoint: `https://${ctx.cfg.hostname}`,
          },
        ],
      });
    }

    // `https://test-feed1.sound-cr.workers.dev/xrpc/app.bsky.feed.getFeedSkeleton` にアクセスしたとき用のJSON
    // 本来はURLの末尾にクエリパラメータ `feed` が来るため、恐らく `feed` 毎に返すフィードを分けなければならない
    const res = {
      feed: [
        {
          post: "at://did:plc:osec57qucip46vc4vm4vdtu6/app.bsky.feed.post/3l3b4yleag32e",
        },
        {
          post: "at://did:plc:osec57qucip46vc4vm4vdtu6/app.bsky.feed.post/3l2ywm62q5w2t",
        },
      ],
      // 必要なら `cursor` も返す
    };
    return Response.json(res);
  },
};