import {
  Column,
  CreateDateColumn,
  Entity,
  Index,
  JoinColumn,
  ManyToOne,
  PrimaryColumn,
  UpdateDateColumn,
} from 'typeorm';
import { AiMessage } from './ai-message.entity';

export type AiFormStatus = 'pending' | 'submitted' | 'expired';

export interface AiFormField {
  name: string;
  label: string;
  type: 'input' | 'textarea' | 'number' | 'select' | 'date';
  required?: boolean;
  placeholder?: string;
  defaultValue?: string | number;
  options?: Array<{ label: string; value: string }>;
}

/**
 * A2UI dynamic form rendered inside an AI assistant message.
 *
 * The schema is validated server-side before persistence; submitted
 * values are validated again at submit time. Full schema copy is also
 * mirrored into the assistant message metadata (`a2uiForm`) so history
 * can render the form without a join.
 */
@Entity('ai_forms')
@Index('idx_ai_forms_message', ['assistantMessageId'])
@Index('idx_ai_forms_user_status', ['userId', 'status'])
export class AiForm {
  @PrimaryColumn({ type: 'varchar', length: 36 })
  id: string;

  @Column({ name: 'conversation_id', type: 'integer' })
  conversationId: number;

  @Column({ name: 'user_id', type: 'integer' })
  userId: number;

  @Column({ name: 'assistant_message_id', type: 'integer' })
  assistantMessageId: number;

  @ManyToOne(() => AiMessage, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'assistant_message_id' })
  assistantMessage: AiMessage | null;

  @Column({ type: 'varchar', length: 50 })
  title: string;

  @Column({ type: 'varchar', length: 200, nullable: true })
  description: string | null;

  @Column({ name: 'submit_label', type: 'varchar', length: 20, default: '提交' })
  submitLabel: string;

  @Column({ name: 'fields_json', type: 'text' })
  fieldsJson: string;

  @Column({ type: 'varchar', length: 20, default: 'pending' })
  status: AiFormStatus;

  @Column({ name: 'submitted_values_json', type: 'text', nullable: true })
  submittedValuesJson: string | null;

  @Column({ name: 'submitted_at', type: 'datetime', nullable: true })
  submittedAt: Date | null;

  @CreateDateColumn({ name: 'created_at', type: 'datetime' })
  createdAt: Date;

  @UpdateDateColumn({ name: 'updated_at', type: 'datetime' })
  updatedAt: Date;
}
