import { pgTable, text, integer, jsonb, uuid, index } from 'drizzle-orm/pg-core';
import { id, tenantId, createdAt, updatedAt, ts, pct } from './_common';
import { aiProposalTypeEnum, aiProposalStatusEnum } from './enums';

/**
 * Every AI output that could change operations is stored as a proposal and
 * must be accepted by a human before it is applied. This is the audit trail
 * for the AI layer.
 */
export const aiProposals = pgTable(
  'ai_proposals',
  {
    id: id(),
    tenantId: tenantId(),
    warehouseId: uuid('warehouse_id'),
    storerId: uuid('storer_id'),
    type: aiProposalTypeEnum('type').notNull(),
    status: aiProposalStatusEnum('status').notNull().default('PROPOSED'),
    title: text('title').notNull(),
    summary: text('summary').notNull(),
    payload: jsonb('payload').notNull().$type<Record<string, unknown>>(),
    evidence: jsonb('evidence').notNull().default({}).$type<Record<string, unknown>>(),
    confidence: pct('confidence'),
    severity: text('severity'),
    model: text('model'),
    promptTokens: integer('prompt_tokens').notNull().default(0),
    completionTokens: integer('completion_tokens').notNull().default(0),
    requestedById: uuid('requested_by_id'),
    decidedById: uuid('decided_by_id'),
    decidedAt: ts('decided_at'),
    decisionNotes: text('decision_notes'),
    appliedRefType: text('applied_ref_type'),
    appliedRefId: uuid('applied_ref_id'),
    expiresAt: ts('expires_at'),
    createdAt: createdAt(),
    updatedAt: updatedAt(),
  },
  (t) => [index('ai_proposals_lookup_idx').on(t.tenantId, t.type, t.status, t.createdAt)],
);

export const aiConversations = pgTable(
  'ai_conversations',
  {
    id: id(),
    tenantId: tenantId(),
    userId: uuid('user_id').notNull(),
    warehouseId: uuid('warehouse_id'),
    title: text('title'),
    createdAt: createdAt(),
    updatedAt: updatedAt(),
  },
  (t) => [index('ai_conversations_user_idx').on(t.tenantId, t.userId)],
);

export const aiMessages = pgTable(
  'ai_messages',
  {
    id: id(),
    tenantId: tenantId(),
    conversationId: uuid('conversation_id').notNull().references(() => aiConversations.id, { onDelete: 'cascade' }),
    role: text('role').notNull(),
    content: text('content').notNull(),
    toolCalls: jsonb('tool_calls').$type<unknown[]>(),
    promptTokens: integer('prompt_tokens').notNull().default(0),
    completionTokens: integer('completion_tokens').notNull().default(0),
    createdAt: createdAt(),
  },
  (t) => [index('ai_messages_conv_idx').on(t.conversationId, t.createdAt)],
);
