import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { ReportDefinition } from './report-definition.entity';

/**
 * Custom Report Entity (schema: reports.custom_reports)
 *
 * User-personalized reports based on existing definitions.
 * Stores custom columns, filters, grouping, and sorting preferences.
 */
@Entity({ name: 'custom_reports', schema: 'reports' })
export class CustomReport {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Index()
  @Column({ name: 'tenant_id', type: 'uuid' })
  tenantId: string;

  @Index()
  @Column({ name: 'owner_id', type: 'uuid' })
  ownerId: string;

  @Column({ name: 'base_definition_id', type: 'uuid', nullable: true })
  baseDefinitionId: string | null;

  @Column({ name: 'name', type: 'varchar', length: 255 })
  name: string;

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

  @Column({ name: 'custom_columns', type: 'jsonb', default: '[]' })
  customColumns: Record<string, any>[];

  @Column({ name: 'custom_filters', type: 'jsonb', default: '[]' })
  customFilters: Record<string, any>[];

  @Column({ name: 'custom_grouping', type: 'jsonb', default: '[]' })
  customGrouping: Record<string, any>[];

  @Column({ name: 'custom_sorting', type: 'jsonb', default: '[]' })
  customSorting: Record<string, any>[];

  @Index()
  @Column({ name: 'is_favorite', type: 'boolean', default: false })
  isFavorite: boolean;

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

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

  // Relations
  @ManyToOne(() => ReportDefinition, (definition) => definition.customReports, { onDelete: 'SET NULL' })
  @JoinColumn({ name: 'base_definition_id' })
  baseDefinition: ReportDefinition | null;
}
