import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
  OneToMany,
  JoinColumn,
  Unique,
} from 'typeorm';
import type { PlatformType, AccountStatus, ProxyConfig } from '@media-manager/shared';
import { User } from './User.js';
import { AccountGroup } from './AccountGroup.js';
import { PublishResult } from './PublishResult.js';
import { Comment } from './Comment.js';
import { AnalyticsData } from './AnalyticsData.js';

@Entity('platform_accounts')
@Unique('uk_user_platform_account', ['userId', 'platform', 'accountId'])
export class PlatformAccount {
  @PrimaryGeneratedColumn()
  id!: number;

  @Column({ type: 'int', name: 'user_id' })
  userId!: number;

  @Column({
    type: 'enum',
    enum: ['douyin', 'kuaishou', 'weixin_video', 'xiaohongshu', 'bilibili', 'toutiao', 'baijiahao', 'qie', 'dayuhao'],
  })
  platform!: PlatformType;

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

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

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

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

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

  @Column({ type: 'text', nullable: true, name: 'cookie_data' })
  cookieData!: string | null;

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

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

  @Column({ type: 'json', nullable: true, name: 'proxy_config' })
  proxyConfig!: ProxyConfig | null;

  @Column({ type: 'int', nullable: true, name: 'group_id' })
  groupId!: number | null;

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

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

  // 关联
  @ManyToOne(() => User, (user) => user.platformAccounts, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'user_id' })
  user!: User;

  @ManyToOne(() => AccountGroup, (group) => group.accounts, { onDelete: 'SET NULL' })
  @JoinColumn({ name: 'group_id' })
  group!: AccountGroup | null;

  @OneToMany(() => PublishResult, (result) => result.account)
  publishResults!: PublishResult[];

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

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