import { boolean, integer, jsonb, pgTable, text, timestamp } from "drizzle-orm/pg-core";

const revision = () => integer("revision").notNull().default(1);
const createdAt = () =>
  timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow();

export const projects = pgTable("projects", {
  id: text("id").primaryKey(),
  name: text("name").notNull().default(""),
  status: text("status").notNull().default("draft"),
  revision: revision(),
  createdAt: createdAt(),
});
export const projectVisionVersions = pgTable("project_vision_versions", {
  id: text("id").primaryKey(),
  projectId: text("project_id").notNull(),
  sequence: integer("sequence").notNull(),
  supersedesId: text("supersedes_id"),
  summary: text("summary").notNull().default(""),
  createdAt: createdAt(),
});
export const goals = pgTable("goals", {
  id: text("id").primaryKey(),
  projectId: text("project_id").notNull(),
  title: text("title").notNull().default(""),
  description: text("description"),
  status: text("status").notNull().default("draft"),
  priority: integer("priority"),
  targetDate: text("target_date"),
  successCriteria: jsonb("success_criteria").notNull().default([]),
  revision: revision(),
  createdAt: createdAt(),
});
export const plans = pgTable("plans", {
  id: text("id").primaryKey(),
  projectId: text("project_id").notNull(),
  title: text("title").notNull().default(""),
  status: text("status").notNull().default("draft"),
  revision: revision(),
  createdAt: createdAt(),
});
export const planRevisions = pgTable("plan_revisions", {
  id: text("id").primaryKey(),
  planId: text("plan_id").notNull(),
  projectId: text("project_id").notNull(),
  sequence: integer("sequence").notNull(),
  title: text("title").notNull().default(""),
  projectVisionVersionId: text("project_vision_version_id"),
  goalIds: jsonb("goal_ids").notNull().default([]),
  createdAt: createdAt(),
});
export const tasks = pgTable("tasks", {
  id: text("id").primaryKey(),
  projectId: text("project_id").notNull(),
  planRevisionId: text("plan_revision_id").notNull(),
  title: text("title").notNull().default(""),
  status: text("status").notNull().default("planned"),
  dependencyIds: jsonb("dependency_ids").notNull().default([]),
  goalIds: jsonb("goal_ids").notNull().default([]),
  revision: revision(),
  createdAt: createdAt(),
});
export const factoryRuns = pgTable("factory_runs", {
  id: text("id").primaryKey(),
  projectId: text("project_id").notNull(),
  planRevisionId: text("plan_revision_id").notNull(),
  status: text("status").notNull().default("planned"),
  reason: text("reason"),
  revision: revision(),
  createdAt: createdAt(),
});
export const agentRuns = pgTable("agent_runs", {
  id: text("id").primaryKey(),
  factoryRunId: text("factory_run_id").notNull(),
  taskId: text("task_id").notNull(),
  status: text("status").notNull().default("planned"),
  reason: text("reason"),
  revision: revision(),
  createdAt: createdAt(),
});
export const workspaces = pgTable("workspaces", {
  id: text("id").primaryKey(),
  projectId: text("project_id").notNull(),
  revision: revision(),
  createdAt: createdAt(),
});
export const attempts = pgTable("attempts", {
  id: text("id").primaryKey(),
  agentRunId: text("agent_run_id").notNull(),
  workspaceId: text("workspace_id").notNull(),
  status: text("status").notNull().default("created"),
  providerId: text("provider_id"),
  accountId: text("account_id"),
  model: text("model"),
  revision: revision(),
  createdAt: createdAt(),
});
export const changeSets = pgTable("change_sets", {
  id: text("id").primaryKey(),
  projectId: text("project_id").notNull(),
  taskId: text("task_id").notNull(),
  producerAttemptId: text("producer_attempt_id").notNull(),
  baseIdentity: text("base_identity").notNull(),
  candidateDigest: text("candidate_digest").notNull(),
  repositoryId: text("repository_id"),
  revision: revision(),
  status: text("status").notNull().default("collecting"),
  createdAt: createdAt(),
});
export const reviews = pgTable("reviews", {
  id: text("id").primaryKey(),
  changeSetId: text("change_set_id").notNull(),
  candidateDigest: text("candidate_digest").notNull(),
  reviewerPrincipalId: text("reviewer_principal_id").notNull().default("system"),
  status: text("status").notNull().default("requested"),
  disposition: text("disposition"),
  createdAt: createdAt(),
});
export const decisions = pgTable("decisions", {
  id: text("id").primaryKey(),
  projectId: text("project_id"),
  revision: revision(),
  createdAt: createdAt(),
});
export const approvals = pgTable("approvals", {
  id: text("id").primaryKey(),
  decisionId: text("decision_id"),
  revision: revision(),
  createdAt: createdAt(),
});
export const credentialReferences = pgTable("credential_references", {
  id: text("id").primaryKey(),
  secretStoreKey: text("secret_store_key").notNull(),
  secretVersion: text("secret_version"),
  createdAt: createdAt(),
});
export const connections = pgTable("connections", {
  id: text("id").primaryKey(),
  providerId: text("provider_id").notNull(),
  credentialReferenceId: text("credential_reference_id").notNull(),
  status: text("status").notNull(),
  accountIdentity: text("account_identity"),
  capabilities: jsonb("capabilities").notNull().default([]),
  resources: jsonb("resources").notNull().default([]),
  revision: revision(),
  createdAt: createdAt(),
});
export const configurationDefinitions = pgTable("configuration_definitions", {
  key: text("key").primaryKey(),
  schemaVersion: integer("schema_version").notNull(),
  definition: jsonb("definition").notNull(),
  createdAt: createdAt(),
});
export const configurationOverrides = pgTable("configuration_overrides", {
  definitionKey: text("definition_key").notNull(),
  scopeType: text("scope_type").notNull(),
  scopeId: text("scope_id").notNull(),
  value: jsonb("value").notNull(),
  resourceRevision: revision(),
  setBy: text("set_by").notNull(),
  setAt: timestamp("set_at", { withTimezone: true, mode: "string" }).notNull(),
});
export const businessEvents = pgTable("business_events", {
  id: text("id").primaryKey(),
  type: text("type").notNull(),
  schemaVersion: integer("schema_version").notNull(),
  occurredAt: timestamp("occurred_at", { withTimezone: true, mode: "string" }).notNull(),
  aggregateType: text("aggregate_type").notNull(),
  aggregateId: text("aggregate_id").notNull(),
  aggregateRevision: integer("aggregate_revision").notNull(),
  projectId: text("project_id"),
  principalId: text("principal_id"),
  correlationId: text("correlation_id").notNull(),
  causationId: text("causation_id"),
  payload: jsonb("payload").notNull(),
});
export const auditRecords = pgTable("audit_records", {
  id: text("id").primaryKey(),
  occurredAt: timestamp("occurred_at", { withTimezone: true, mode: "string" }).notNull(),
  principalId: text("principal_id").notNull(),
  action: text("action").notNull(),
  targetType: text("target_type").notNull(),
  targetId: text("target_id").notNull(),
  projectId: text("project_id"),
  disposition: text("disposition").notNull(),
  policyId: text("policy_id"),
  policyRevision: integer("policy_revision"),
  decisionId: text("decision_id"),
  approvalId: text("approval_id"),
  correlationId: text("correlation_id").notNull(),
  safeMetadata: jsonb("safe_metadata").notNull().default({}),
});
export const outboxMessages = pgTable("outbox_messages", {
  id: text("id").primaryKey(),
  topic: text("topic").notNull(),
  payload: jsonb("payload").notNull(),
  occurredAt: timestamp("occurred_at", { withTimezone: true, mode: "string" }).notNull(),
  published: boolean("published").notNull().default(false),
  publishedAt: timestamp("published_at", { withTimezone: true, mode: "string" }),
  attempts: integer("attempts").notNull().default(0),
});

export const schema = {
  projects,
  projectVisionVersions,
  goals,
  plans,
  planRevisions,
  tasks,
  factoryRuns,
  agentRuns,
  workspaces,
  attempts,
  changeSets,
  reviews,
  decisions,
  approvals,
  credentialReferences,
  connections,
  configurationDefinitions,
  configurationOverrides,
  businessEvents,
  auditRecords,
  outboxMessages,
};
