/**
 * StorageFolder Entity
 * Hierarchical folder structure within buckets
 * Compatible with erp-core folder.entity
 *
 * @module Storage
 */

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
  OneToMany,
  Unique,
} from 'typeorm';
import { StorageBucket } from './bucket.entity';

@Entity({ name: 'folders', schema: 'storage' })
@Unique(['tenantId', 'bucketId', 'path'])
export class StorageFolder {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Index()
  @Column({ name: 'tenant_id', type: 'uuid' })
  tenantId: string;

  @Index()
  @Column({ name: 'bucket_id', type: 'uuid' })
  bucketId: string;

  @Index()
  @Column({ name: 'parent_id', type: 'uuid', nullable: true })
  parentId: string;

  @Index()
  @Column({ name: 'path', type: 'text' })
  path: string;

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

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

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

  @Column({ name: 'color', type: 'varchar', length: 7, nullable: true })
  color: string;

  @Column({ name: 'icon', type: 'varchar', length: 50, nullable: true })
  icon: string;

  @Column({ name: 'is_private', type: 'boolean', default: false })
  isPrivate: boolean;

  @Column({ name: 'owner_id', type: 'uuid', nullable: true })
  ownerId: string;

  @Column({ name: 'file_count', type: 'int', default: 0 })
  fileCount: number;

  @Column({ name: 'total_size_bytes', type: 'bigint', default: 0 })
  totalSizeBytes: number;

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

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

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

  @ManyToOne(() => StorageBucket, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'bucket_id' })
  bucket: StorageBucket;

  @ManyToOne(() => StorageFolder, { nullable: true, onDelete: 'CASCADE' })
  @JoinColumn({ name: 'parent_id' })
  parent: StorageFolder;

  @OneToMany(() => StorageFolder, (folder) => folder.parent)
  children: StorageFolder[];
}
