import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  Index,
  ManyToOne,
  JoinColumn,
  Unique,
} from 'typeorm';
import { User } from './user.entity.js';
import { Tenant } from './tenant.entity.js';

@Entity({ schema: 'auth', name: 'oauth_providers' })
@Unique(['provider', 'providerUserId'])
@Index('idx_oauth_providers_user', ['userId'])
@Index('idx_oauth_providers_provider', ['provider', 'providerUserId'])
@Index('idx_oauth_providers_email', ['providerEmail'])
export class OAuthProvider {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

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

  // Provider info
  @Column({ type: 'varchar', length: 50, nullable: false })
  provider: string;

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

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

  // Tokens (encrypted)
  @Column({ type: 'text', nullable: true, name: 'access_token_encrypted' })
  accessTokenEncrypted: string | null;

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

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

  // Profile data from provider
  @Column({ type: 'jsonb', default: '{}', name: 'profile_data' })
  profileData: Record<string, any>;

  // Timestamps
  @Column({
    type: 'timestamptz',
    nullable: true,
    name: 'linked_at',
    default: () => 'CURRENT_TIMESTAMP',
  })
  linkedAt: Date | null;

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

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

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

  @ManyToOne(() => Tenant, {
    onDelete: 'CASCADE',
  })
  @JoinColumn({ name: 'tenant_id' })
  tenant: Tenant;
}
