// Template: Paperclip plugin worker entry
// Generated by `npm create paperclip-plugin@latest` or /paperclip:generate-adapter <name> plugin.
// Docs: https://docs.paperclip.ing/  SDK: @paperclipai/plugin-sdk

import { definePlugin, runWorker, z } from "@paperclipai/plugin-sdk";

// --- Config --------------------------------------------------------------
// Declare the shape of this plugin's per-instance configuration. Paperclip
// surfaces these fields in the UI. Use zod so validation is shared with the
// manifest's JSON Schema.

const configSchema = z.object({
  apiKeyRef: z.string().describe("Secret reference for the upstream API key"),
  baseUrl: z.string().url().default("https://api.example.com"),
});

// --- Plugin --------------------------------------------------------------

const plugin = definePlugin({
  async setup(ctx) {
    ctx.logger.info("plugin.starting", { plugin: ctx.manifest.id });

    // React to platform events
    ctx.events.on("issue.created", async (event) => {
      const cfg = await ctx.config.get();
      const apiKey = await ctx.secrets.resolve(cfg.apiKeyRef);

      const res = await ctx.http.fetch(`${cfg.baseUrl}/issues`, {
        method: "POST",
        headers: { Authorization: `Bearer ${apiKey}` },
        body: JSON.stringify({ entityId: event.entityId }),
      });

      if (!res.ok) {
        ctx.logger.warn("upstream.rejected", { status: res.status });
      }
    });

    // Register a background job
    ctx.jobs.register("full-sync", async (job) => {
      ctx.logger.info("full-sync.start", { runId: job.runId });
      // TODO: implement sync logic using ctx.entities / ctx.state
    });

    // Provide data the dashboard can query
    ctx.data.register("sync-health", async ({ companyId }) => {
      const last = await ctx.state.get({
        scopeKind: "company",
        scopeId: String(companyId),
        stateKey: "last-sync-at",
      });
      return { lastSync: last };
    });
  },

  async onHealth() {
    // Return quickly. Don't call upstream from here.
    return { status: "ok" };
  },
});

export default plugin;
runWorker(plugin, import.meta.url);
