import {
    Entity,
    PrimaryGeneratedColumn,
    Column,
    CreateDateColumn,
    UpdateDateColumn,
    OneToMany,
    OneToOne,
    JoinColumn,
    ManyToOne,
} from 'typeorm';
import { PlanPermission } from './plan-permission.entity';
import { Subscription } from './subscription.entity';

export enum Interval {
    MONTH = 'month',
    YEAR = 'year'
}

@Entity('plans')
export class Plan {
    @PrimaryGeneratedColumn('uuid')
    id: string;

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

    @Column({ type: 'varchar', length: 255, unique: true })
    slug: string;

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

    @Column({ type: 'varchar', length: 50, comment: "Free,Primium" })
    plan_type: string;

    @Column({ type: 'varchar', length: 255, nullable: true })
    product_id: string;

    @Column({ type: 'varchar', length: 255, nullable: true })
    year_price_id: string;

    @Column({ type: 'varchar', length: 255, nullable: true })
    month_price_id: string;

    @Column({ type: 'jsonb', nullable: true })
    product_response: Record<string, any>;

    @Column({ type: 'jsonb', nullable: true })
    year_price_response: Record<string, any>;

    @Column({ type: 'jsonb', nullable: true })
    month_price_response: Record<string, any>;

    @Column({ type: 'varchar', length: 10 })
    currency: string;

    @Column({ type: 'decimal', precision: 10, scale: 2, default: 0.00 })
    year_amount: number;

    @Column({ type: 'decimal', precision: 10, scale: 2, default: 0.00 })
    month_amount: number;

    @Column({ type: 'enum', enum: Interval, default: Interval.MONTH })
    interval: string;

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

    @Column({ type: 'uuid', nullable: true })
    created_by: string;

    @Column({ type: 'uuid', nullable: true })
    updated_by: string;

    @Column({ type: 'int', default: 1 })
    priority: number;

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

    @Column({ type: 'int', default: 0 })
    trial_days: number;

    @Column({ type: 'uuid', nullable: true, default: null })
    parent_plan_id: string | null;

    @ManyToOne(() => Plan, (plan) => plan.children, { nullable: true, onDelete: 'SET NULL' })
    @JoinColumn({ name: 'parent_plan_id' }) // defines the foreign key column
    parent: Plan;

    @OneToMany(() => Plan, (plan) => plan.parent)
    children: Plan[];

    @Column({ type: 'varchar', nullable: true, length: 255 })
    discount_label: string;

    @CreateDateColumn({ type: 'timestamp' })
    created_at: Date;

    @UpdateDateColumn({ type: 'timestamp' })
    updated_at: Date;

    @OneToMany(() => PlanPermission, (permission) => permission.plan)
    permission: PlanPermission[];

    @OneToMany(() => Subscription, (sub) => sub.plan)
    subscription: Subscription[];
}