import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { User } from './user.entity';
import { OAuthProvider } from './oauth-provider.entity';

@Entity({ schema: 'auth', name: 'oauth_user_links' })
@Index('idx_oauth_links_user', ['userId'])
@Index('idx_oauth_links_provider', ['providerId'])
@Index('idx_oauth_links_oauth_uid', ['oauthUid'])
export class OAuthUserLink {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ type: 'uuid', nullable: false, name: 'user_id' })
  userId: string;

  @Column({ type: 'uuid', nullable: false, name: 'provider_id' })
  providerId: string;

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

  @Column({ type: 'varchar', length: 255, nullable: true, name: 'oauth_email' })
  oauthEmail: string | null;

  @Column({ type: 'text', nullable: true, name: 'access_token' })
  accessToken: string | null;

  @Column({ type: 'text', nullable: true, name: 'refresh_token' })
  refreshToken: string | null;

  @Column({ type: 'text', nullable: true, name: 'id_token' })
  idToken: string | null;

  @Column({ type: 'timestamptz', nullable: true, name: 'token_expires_at' })
  tokenExpiresAt: Date | null;

  @Column({ type: 'jsonb', nullable: true, name: 'raw_userinfo' })
  rawUserinfo: Record<string, unknown> | null;

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

  @Column({ type: 'integer', default: 0, nullable: false, name: 'login_count' })
  loginCount: number;

  @ManyToOne(() => User, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'user_id' })
  user: User;

  @ManyToOne(() => OAuthProvider, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'provider_id' })
  provider: OAuthProvider;

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

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