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

@Entity({ schema: 'auth', name: 'oauth_states' })
@Index('idx_oauth_states_state', ['state'])
@Index('idx_oauth_states_expires', ['expiresAt'])
export class OAuthState {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ type: 'varchar', length: 64, nullable: false, unique: true })
  state: string;

  // PKCE
  @Column({ type: 'varchar', length: 128, nullable: true, name: 'code_verifier' })
  codeVerifier: string | null;

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

  @Column({ type: 'varchar', length: 500, nullable: false, name: 'redirect_uri' })
  redirectUri: string;

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

  // Vinculación con usuario existente (para linking)
  @Column({ type: 'uuid', nullable: true, name: 'link_user_id' })
  linkUserId: string | null;

  // Metadata
  @Column({ type: 'inet', nullable: true, name: 'ip_address' })
  ipAddress: string | null;

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

  // Relaciones
  @ManyToOne(() => OAuthProvider)
  @JoinColumn({ name: 'provider_id' })
  provider: OAuthProvider;

  @ManyToOne(() => User, { nullable: true })
  @JoinColumn({ name: 'link_user_id' })
  linkUser: User | null;

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

  @Column({ type: 'timestamptz', nullable: false, name: 'expires_at' })
  expiresAt: Date;

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