import { z } from 'zod';
import { requireUser, getWorkspace } from '@/lib/auth';
import { NotesGrantForm } from '@/components/notes/notes-grant-form';

const credentials = z.array(z.object({ id: z.uuid(), name: z.string(), revoked_at: z.string().nullable().optional() }));
export default async function NotesAccessPage() {
  const { supabase } = await requireUser();
  const workspace = await getWorkspace();
  if (!workspace || workspace.role === 'member') return <p>Only workspace owners and admins can manage notes access.</p>;
  const [keys, connections] = await Promise.all([
    supabase.rpc('list_api_keys', { target: workspace.organization.id }),
    supabase.rpc('list_mcp_connections'),
  ]);
  if (keys.error || connections.error) throw new Error('Credential list unavailable. Try again.');
  return <section className="mx-auto max-w-2xl space-y-6 p-6">
    <h1 className="text-2xl font-semibold">Notes integration access</h1>
    <p>Selected workspace: {workspace.organization.name}. IDs below are identifiers, not secret keys. Each grant allows reading the latest 50 notes. It never allows creating a note.</p>
    <h2>Workspace API keys</h2>
    <ul>{credentials.parse(keys.data).filter(k => !k.revoked_at).map(k => <li key={k.id}>{k.name}: <code>{k.id}</code></li>)}</ul>
    <h2>Your OAuth connections</h2>
    <p>The server accepts only a connection belonging to you and the selected workspace. Connections to other workspaces cannot receive this grant.</p>
    <ul>{credentials.parse(connections.data).filter(k => !k.revoked_at).map(k => <li key={k.id}>{k.name}: <code>{k.id}</code></li>)}</ul>
    <NotesGrantForm workspaceId={workspace.organization.id} />
  </section>;
}
