/**
 * Subscription ORM Entity (Infrastructure Layer)
 *
 * TypeORM entity for subscription persistence.
 * Represents organization subscriptions with plan and Stripe integration.
 */

import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
  OneToMany,
  JoinColumn,
  Index,
} from 'typeorm';
import { OrganizationOrmEntity } from './organization.orm-entity';
import { LicenseOrmEntity } from './license.orm-entity';

export type SubscriptionPlanOrmType = 'BRONZE' | 'SILVER' | 'GOLD' | 'PLATINIUM';

export type SubscriptionStatusOrmType =
  | 'ACTIVE'
  | 'PAST_DUE'
  | 'CANCELED'
  | 'INCOMPLETE'
  | 'INCOMPLETE_EXPIRED'
  | 'TRIALING'
  | 'UNPAID'
  | 'PAUSED';

@Entity('subscriptions')
@Index('idx_subscriptions_organization_id', ['organizationId'])
@Index('idx_subscriptions_stripe_customer_id', ['stripeCustomerId'])
@Index('idx_subscriptions_stripe_subscription_id', ['stripeSubscriptionId'])
@Index('idx_subscriptions_plan', ['plan'])
@Index('idx_subscriptions_status', ['status'])
export class SubscriptionOrmEntity {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ name: 'organization_id', type: 'uuid', unique: true })
  organizationId: string;

  @ManyToOne(() => OrganizationOrmEntity, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'organization_id' })
  organization: OrganizationOrmEntity;

  // Plan information
  @Column({
    type: 'enum',
    enum: ['BRONZE', 'SILVER', 'GOLD', 'PLATINIUM'],
    default: 'BRONZE',
  })
  plan: SubscriptionPlanOrmType;

  @Column({
    type: 'enum',
    enum: [
      'ACTIVE',
      'PAST_DUE',
      'CANCELED',
      'INCOMPLETE',
      'INCOMPLETE_EXPIRED',
      'TRIALING',
      'UNPAID',
      'PAUSED',
    ],
    default: 'ACTIVE',
  })
  status: SubscriptionStatusOrmType;

  // Stripe integration
  @Column({ name: 'stripe_customer_id', type: 'varchar', length: 255, nullable: true })
  stripeCustomerId: string | null;

  @Column({
    name: 'stripe_subscription_id',
    type: 'varchar',
    length: 255,
    nullable: true,
    unique: true,
  })
  stripeSubscriptionId: string | null;

  // Billing period
  @Column({ name: 'current_period_start', type: 'timestamp', nullable: true })
  currentPeriodStart: Date | null;

  @Column({ name: 'current_period_end', type: 'timestamp', nullable: true })
  currentPeriodEnd: Date | null;

  @Column({ name: 'cancel_at_period_end', type: 'boolean', default: false })
  cancelAtPeriodEnd: boolean;

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

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

  // Relations
  @OneToMany(() => LicenseOrmEntity, license => license.subscription)
  licenses: LicenseOrmEntity[];
}
