import { Transform } from 'class-transformer';
import { isURL } from 'class-validator';
import { Column, Entity, OneToMany } from 'typeorm';
import { CoreEntity } from './core/core-entity';
import { PublistHistory } from './publist-history.entity';

@Entity('products')
export class Product extends CoreEntity {
  @Column('varchar', { array: true, default: [] })
  @Transform(({ obj, value }) => {
    if (!value) return [];

    const title = obj.title;
    const env = process.env.ENV || 'production';
    const prefix = process.env.PREFIX_VERSION || '/api';
    const port = process.env.APP_PORT || '4000';

    return (value as string[]).map((item) => {
      // Nếu đã là URL đầy đủ thì trả về nguyên xi
      if (/^https?:\/\//i.test(item)) {
        return item;
      }

      const path = `medias/products/${title.toLowerCase().replaceAll(' ', '-')}/${item}`;

      if (env === 'dev') {
        return `http://localhost:${port}${prefix}/${path}`;
      }
      return path;
    });
  })
  images: string[];

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

  @Column({ type: 'numeric' })
  price: number;

  @Column({ type: 'varchar' })
  category: string;

  @Column({ type: 'varchar' })
  condition: string;

  @Column({ type: 'varchar', nullable: true })
  brand?: string;

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

  @Column('varchar', { array: true, default: [] })
  tags?: string[];

  @Column({ type: 'varchar', unique: true })
  sku: string;

  @Column({ type: 'varchar', nullable: true })
  location?: string;

  @Column({ type: 'bool', default: false })
  status: boolean;

  @OneToMany(() => PublistHistory, (publistHistory) => publistHistory.product)
  histories: PublistHistory[];
}
