import { Entity, PrimaryGeneratedColumn, Column, ManyToMany, JoinTable, CreateDateColumn, UpdateDateColumn, ManyToOne, JoinColumn } from 'typeorm';
import { Role } from './role.entity';
import { File } from '@/server/modules/files/file.entity';
import { DeleteStatus, DisabledStatus } from '@/share/types';

@Entity({ name: 'users' })
export class UserEntity {
  @PrimaryGeneratedColumn({ unsigned: true, comment: '用户ID' })
  id!: number;

  @Column({ name: 'username', type: 'varchar', length: 255, unique: true, comment: '用户名' })
  username!: string;

  @Column({ name: 'password', type: 'varchar', length: 255, comment: '密码' })
  password!: string;

  @Column({ name: 'phone', type: 'varchar', length: 255, nullable: true, comment: '手机号' })
  phone!: string | null;

  @Column({ name: 'email', type: 'varchar', length: 255, nullable: true, comment: '邮箱' })
  email!: string | null;

  @Column({ name: 'nickname', type: 'varchar', length: 255, nullable: true, comment: '昵称' })
  nickname!: string | null;

  @Column({ name: 'name', type: 'varchar', length: 255, nullable: true, comment: '真实姓名' })
  name!: string | null;

  @Column({ name: 'avatar_file_id', type: 'int', unsigned: true, nullable: true, comment: '头像文件ID' })
  avatarFileId!: number | null;

  @ManyToOne(() => File, { nullable: true })
  @JoinColumn({ name: 'avatar_file_id', referencedColumnName: 'id' })
  avatarFile!: File | null;

  @Column({ name: 'is_disabled', type: 'int', default: DisabledStatus.ENABLED, comment: '是否禁用(0:启用,1:禁用)' })
  isDisabled!: DisabledStatus;

  @Column({ name: 'is_deleted', type: 'int', default: DeleteStatus.NOT_DELETED, comment: '是否删除(0:未删除,1:已删除)' })
  isDeleted!: DeleteStatus;

  @Column({ name: 'user_type', type: 'varchar', length: 20, default: 'basic', comment: '用户类型: basic, premium' })
  userType!: string;

  @Column({ name: 'remaining_count', type: 'int', default: 5, comment: '剩余文档处理次数' })
  remainingCount!: number;

  @Column({ name: 'total_usage', type: 'int', default: 0, comment: '总使用次数' })
  totalUsage!: number;

  @Column({ name: 'monthly_usage', type: 'int', default: 0, comment: '本月使用次数' })
  monthlyUsage!: number;

  @Column({ name: 'expire_at', type: 'timestamp', nullable: true, comment: '会员有效期' })
  expireAt!: Date | null;

  @Column({ name: 'last_used_at', type: 'timestamp', nullable: true, comment: '最后使用时间' })
  lastUsedAt!: Date | null;

  @ManyToMany(() => Role)
  @JoinTable()
  roles!: Role[];

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

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

  constructor(partial?: Partial<UserEntity>) {
    Object.assign(this, partial);
  }
}

export { UserEntity as User }