import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  ManyToOne,
  OneToMany,
  JoinColumn,
  BeforeInsert,
  BeforeUpdate,
} from 'typeorm';

@Entity('service')
export class ServiceEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ unique: true })
  name: string;

  @Column({ type: 'text' })
  subName: string;

  @Column({ type: 'text' })
  expectedOutcomeMessage: string;

  @Column({ unique: true })
  slug: string;

  @Column({ nullable: true })
  badge: string; // e.g., 'LAYANAN UTAMA'

  @Column({ nullable: true })
  thumbnailUrl: string; // URL for the image shown on the card

  @Column({ type: 'text', nullable: true })
  description: string; // Short text for the card

  @Column({ type: 'text' })
  longDescription: string;

  @Column({ type: 'simple-array', nullable: true })
  tags: string[];

  @Column({ nullable: true })
  footerText: string; // e.g., 'Program kesehatan individual'

  @Column({ type: 'text', nullable: true })
  landingHtml: string; // Full HTML for the individual service page

  @Column({ nullable: true })
  parentId: number;

  @ManyToOne(() => ServiceEntity, (service) => service.children, {
    nullable: true,
    onDelete: 'CASCADE',
  })
  @JoinColumn({ name: 'parentId' })
  parent: ServiceEntity;

  @OneToMany(() => ServiceEntity, (service) => service.parent)
  children: ServiceEntity[];

  @BeforeInsert()
  @BeforeUpdate()
  generateSlug() {
    if (this.name) {
      this.slug = this.name
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-') // Replace non-alphanumeric characters with hyphens
        .replace(/(^-|-$)+/g, ''); // Remove leading or trailing hyphens
    }
  }
}
