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

export type AiReviewStatus = 'pending' | 'submitted' | 'expired';
// aislop-ignore-next-line: duplicate-type-declaration -- 与前端 AiChat 的 API 契约保持一致
export type AiReviewSectionStatus = 'pending' | 'submitted' | 'failed' | 'skipped';
// aislop-ignore-next-line: duplicate-type-declaration -- 与前端 AiChat 的 API 契约保持一致
export type AiReviewSectionType = 'students' | 'rooms' | 'transfers' | 'checkins';

// aislop-ignore-next-line: duplicate-type-declaration -- 与前端 AiChat 的 API 契约保持一致
export interface AiReviewColumn {
  key: string;
  title: string;
}

// aislop-ignore-next-line: duplicate-type-declaration -- 与前端 AiChat 的 API 契约保持一致
export interface AiReviewRow {
  [key: string]: string | number | boolean | null;
}

export interface AiReviewSection {
  /** 唯一实例 ID（同一业务类型可有多张 sheet，每个 key 唯一） */
  key: string;
  /** 业务类型：students 学生 / rooms 宿舍 / transfers 换宿 / checkins 入住记录 */
  type: AiReviewSectionType;
  title: string;
  kind: 'table';
  /** 来源工作表名（可选） */
  sheet?: string;
  columns: AiReviewColumn[];
  rows: AiReviewRow[];
  issues: string[];
  status?: AiReviewSectionStatus;
  resultSummary?: string | null;
  submittedAt?: string | null;
}

@Entity('ai_reviews')
@Index('idx_ai_reviews_message', ['assistantMessageId'])
@Index('idx_ai_reviews_user_status', ['userId', 'status'])
export class AiReview {
  @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: 100 })
  title: string;

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

  @Column({ name: 'sections_json', type: 'text' })
  sectionsJson: string;

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

  @Column({ name: 'result_summary', type: 'text', nullable: true })
  resultSummary: 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;
}
