// entities/post.entity.ts
import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
  JoinColumn,
  BeforeInsert,
  BeforeUpdate,
  RelationId,
} from 'typeorm';
import { Category } from './category.entity';
import { User } from './user.entity';
import slugify from 'slugify';

@Entity('posts')
export class Post {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  title_vi: string;

  @Column()
  title_en: string;

  @Column({ nullable: true })
  title_zh: string;

  @Column('text')
  content_vi: string;

  @Column('text', { nullable: true })
  content_en: string;

  @Column('text', { nullable: true })
  content_zh: string;

  @Column()
  slug: string;

  @Column({ nullable: true })
  image: string;

  @ManyToOne(() => Category, (category) => category.posts, {
    nullable: true,
    onDelete: 'SET NULL',
  })
  @JoinColumn({ name: 'category_id' })
  category: Category;

  @Column({ type: 'int', nullable: true })
  category_id: number;

  @ManyToOne(() => User, (user) => user.posts, {
    nullable: true,
    onDelete: 'SET NULL',
  })
  @JoinColumn({ name: 'author_id' })
  author: User;

  @Column({ type: 'int', nullable: true })
  author_id: number;

  @Column({ type: 'date' })
  publish_date: Date;

  @CreateDateColumn({ name: 'created_at' })
  created_at: Date;

  @UpdateDateColumn({ name: 'updated_at' })
  updated_at: Date;

  @BeforeInsert()
  @BeforeUpdate()
  generateSlug() {
    if (this.title_vi) {
      this.slug = slugify(this.title_vi, {
        lower: true,
        strict: true,
        locale: 'vi',
      });
    }

    if (!this.publish_date) {
      this.publish_date = new Date();
    }
  }
}
