import { ColumnDecimalTransformer } from '@core/utils'
import { Column, Entity, OneToMany } from 'typeorm'
import { SoftDeleteEntity } from '../entity'
import { ItemUnit } from './enums'
import { MenuItemCategory } from './item-category.model'

@Entity()
export class MenuItem extends SoftDeleteEntity<MenuItem> {
	/**
	 * Name of the Item
	 */
	@Column({
		type: 'varchar',
		length: 60,
		nullable: false,
	})
	name: string

	/**
	 * Short description
	 */
	@Column({
		type: 'varchar',
		length: 255,
		nullable: true,
	})
	description?: string

	/**
	 * Unit price
	 */
	@Column({
		type: 'decimal',
		nullable: false,
		transformer: new ColumnDecimalTransformer(),
	})
	price: number

	/**
	 * Currency descriptor of unit price e.g PKR, USD, EUR
	 */
	@Column({
		type: 'varchar',
		length: 3,
		nullable: false,
	})
	currency: string

	/**
	 * Amount that represents one unit of item e.g if unit is liter it could be 1.5l for coke
	 */
	@Column({
		type: 'decimal',
		nullable: false,
		transformer: new ColumnDecimalTransformer(),
	})
	amount: number

	/**
	 * The unit that is used to measure amount of item
	 */
	@Column({
		type: 'enum',
		enum: ItemUnit,
		default: ItemUnit.pieces,
		nullable: false,
	})
	unit: ItemUnit

	/**
	 * A list of allergens caused by item
	 */
	@Column({
		type: 'simple-array',
		nullable: true,
	})
	allergens?: string[]

	/**
	 * Cover image url
	 */
	@Column({
		type: 'text',
		nullable: true,
	})
	coverUrl?: string

	/**
	 * True if the Item been archived by user
	 */
	@Column({
		type: 'boolean',
		nullable: false,
		default: false,
	})
	isArchived: boolean

	/**
	 * List of categories
	 */
	@OneToMany(() => MenuItemCategory, (category) => category.item)
	categories: MenuItemCategory[]

	getRootCategories(): MenuItemCategory[] {
		return this.categories.filter((category) => !category.category.parentCategory)
	}

	getSubcategories(): MenuItemCategory[] {
		return this.categories.filter((category) => !!category.category.parentCategory)
	}
}
