import { desc, eq } from "drizzle-orm";
import { z } from "zod";
import { db } from "@/lib/db";
import { getCurrentSession } from "@/lib/session";
import type { ActivityLogEntry, ModuleManifest } from "./module";
import { getEntityType } from "./registry";
import { activityLog } from "./schema";

const activityConfigSchema = z.object({
  limit: z.number().int().min(1).max(50).optional(),
});

async function ActivityWidget({ config }: { config: unknown }) {
  const parsed = activityConfigSchema.parse(config);
  const { household } = await getCurrentSession();

  const entries = await db
    .select()
    .from(activityLog)
    .where(eq(activityLog.householdId, household.id))
    .orderBy(desc(activityLog.createdAt))
    .limit(parsed.limit ?? 20);

  if (entries.length === 0) {
    return <p className="text-sm text-[var(--ink-mute)]">No recent activity</p>;
  }

  return (
    <div className="flex flex-col">
      {entries.map((entry) => {
        const reg = getEntityType(entry.entityType);
        const description =
          reg?.renderActivity?.(entry as ActivityLogEntry) ?? `${entry.action} ${entry.entityType}`;
        return (
          <div key={entry.id} className="activity-row">
            <div className="flex-1 leading-[1.4]">
              <span className="obj">{description}</span>
            </div>
            <time>
              {entry.createdAt.toLocaleDateString(undefined, { month: "short", day: "numeric" })}
            </time>
          </div>
        );
      })}
    </div>
  );
}

const coreManifest: ModuleManifest = {
  id: "_core",
  name: "Core",
  entities: [],
  dashboardWidgets: [
    {
      id: "core.activity",
      title: "Recent activity",
      description: "Latest changes across your household.",
      category: "Core",
      defaultSize: { w: 4, h: 3 },
      minSize: { w: 3, h: 2 },
      defaultPriority: 50,
      configSchema: activityConfigSchema,
      defaultConfig: { limit: 20 },
      resolveConfigOptions: async () => undefined,
      render: (props) => <ActivityWidget {...props} />,
    },
  ],
};

export default coreManifest;
