/**
 * cms blueprint · wiring seam for `@platform-modules/fields` composed with content.
 *
 * Host-owned glue: run the fields migration on the same PGlite client the CMS content
 * fixture uses, then expose a typed Querier for the EAV tables. No package edge content↔fields.
 *
 * AUTHZ obligation (spec §5 / §8.1 — the IDOR floor; NOT exercised by this composition fixture):
 * the engine's `assertCanEditFields` is CAPABILITY-only; it has no owner column. A field-value
 * write onto a `content` entry is an EDIT of that entry, so the host route MUST also enforce the
 * SAME object-level ownership gate `content` enforces on edit — `assertCanModify(actor, action,
 * entry.author, entry.id)` (content/authz.ts: author-or-`canEditAny`) — BEFORE calling
 * setEntityValues / deleteEntityValues. The `fieldsEditor` seeded below is a god-mode capability
 * actor for the swap/cascade proof ONLY; an adopter who maps a non-`canEditAny` author (content's
 * first-class `authorActor` role) to field-editing WITHOUT this gate has a write-IDOR (author-2
 * writes fields on author-1's post). This fixture proves composition + cascade, not route authz.
 */
import { drizzle } from 'drizzle-orm/pglite'
import type { TransactionalDatabase } from '@platform-modules/db'
import {
  fieldsMigrationSql,
  fieldsSchema,
  defineFieldGroup,
  type Actor as FieldsActor,
  type CodeFieldGroup,
  type FieldsSchema,
} from '@platform-modules/fields'
import { createContentDb, type SeededContent } from './content.js'

export type FieldsDb = TransactionalDatabase<FieldsSchema>

export type SeededContentWithFields = SeededContent & {
  fieldsDb: FieldsDb
  fieldsEditor: FieldsActor
  contentAttrsGroup: CodeFieldGroup
}

/** Code-defined group the CMS blueprint mounts for post entries (spec §8.1 subType = entry.type). */
export const contentAttrsGroup = defineFieldGroup({
  key: 'content_attrs',
  label: 'Attributes',
  location: { entityType: 'content', subType: 'post' },
  fields: [{ type: 'text', key: 'material', label: 'Material' }],
})

export async function createContentWithFieldsDb(): Promise<SeededContentWithFields> {
  const seeded = await createContentDb()
  await seeded.client.exec(fieldsMigrationSql())
  const fieldsDb = drizzle(seeded.client, { schema: fieldsSchema }) as unknown as FieldsDb
  return {
    ...seeded,
    fieldsDb,
    fieldsEditor: { id: seeded.editorActor.id, canEditFields: true, canManageGroups: true },
    contentAttrsGroup,
  }
}
