import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  OneToMany,
} from 'typeorm';
import { Company } from './company.entity';
import { User } from './user.entity';
import { Role } from './role.entity';

export enum TenantStatus {
  ACTIVE = 'active',
  SUSPENDED = 'suspended',
  TRIAL = 'trial',
  CANCELLED = 'cancelled',
}

@Entity({ schema: 'auth', name: 'tenants' })
@Index('idx_tenants_subdomain', ['subdomain'])
@Index('idx_tenants_status', ['status'], { where: 'deleted_at IS NULL' })
@Index('idx_tenants_created_at', ['createdAt'])
export class Tenant {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  @Column({ type: 'varchar', length: 100, unique: true, nullable: false })
  subdomain: string;

  @Column({
    type: 'varchar',
    length: 100,
    unique: true,
    nullable: false,
    name: 'schema_name',
  })
  schemaName: string;

  @Column({
    type: 'enum',
    enum: TenantStatus,
    default: TenantStatus.ACTIVE,
    nullable: false,
  })
  status: TenantStatus;

  @Column({ type: 'jsonb', default: {} })
  settings: Record<string, unknown>;

  @Column({ type: 'varchar', length: 50, default: 'basic', nullable: true })
  plan: string;

  @Column({ type: 'integer', default: 10, name: 'max_users' })
  maxUsers: number;

  @OneToMany(() => Company, (company) => company.tenant)
  companies: Company[];

  @OneToMany(() => User, (user) => user.tenant)
  users: User[];

  @OneToMany(() => Role, (role) => role.tenant)
  roles: Role[];

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

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

  @UpdateDateColumn({
    name: 'updated_at',
    type: 'timestamp',
    nullable: true,
  })
  updatedAt: Date | null;

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

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

  @Column({ type: 'uuid', nullable: true, name: 'deleted_by' })
  deletedBy: string | null;
}
