import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  OneToMany,
} from 'typeorm';
import type { UserRole, UserStatus } from '@media-manager/shared';
import { UserToken } from './UserToken.js';
import { AccountGroup } from './AccountGroup.js';
import { PlatformAccount } from './PlatformAccount.js';
import { PublishTask } from './PublishTask.js';
import { Comment } from './Comment.js';
import { AnalyticsData } from './AnalyticsData.js';
import { OperationLog } from './OperationLog.js';

@Entity('users')
export class User {
  @PrimaryGeneratedColumn()
  id!: number;

  @Column({ type: 'varchar', length: 50, unique: true })
  username!: string;

  @Column({ type: 'varchar', length: 100, unique: true, nullable: true })
  email!: string | null;

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

  @Column({ type: 'varchar', length: 500, nullable: true, name: 'avatar_url' })
  avatarUrl!: string | null;

  @Column({ type: 'varchar', length: 50, nullable: true })
  nickname!: string | null;

  @Column({ type: 'enum', enum: ['admin', 'editor', 'operator'], default: 'operator' })
  role!: UserRole;

  @Column({ type: 'enum', enum: ['active', 'disabled', 'pending'], default: 'active' })
  status!: UserStatus;

  @Column({ type: 'timestamp', nullable: true, name: 'last_login_at' })
  lastLoginAt!: Date | null;

  @Column({ type: 'varchar', length: 50, nullable: true, name: 'last_login_ip' })
  lastLoginIp!: string | null;

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

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

  // 关联
  @OneToMany(() => UserToken, (token) => token.user)
  tokens!: UserToken[];

  @OneToMany(() => AccountGroup, (group) => group.user)
  accountGroups!: AccountGroup[];

  @OneToMany(() => PlatformAccount, (account) => account.user)
  platformAccounts!: PlatformAccount[];

  @OneToMany(() => PublishTask, (task) => task.user)
  publishTasks!: PublishTask[];

  @OneToMany(() => Comment, (comment) => comment.user)
  comments!: Comment[];

  @OneToMany(() => AnalyticsData, (data) => data.user)
  analyticsData!: AnalyticsData[];

  @OneToMany(() => OperationLog, (log) => log.user)
  operationLogs!: OperationLog[];
}
