import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
  Unique,
} from 'typeorm';
import { Branch } from './branch.entity';

export type AssignmentType = 'primary' | 'secondary' | 'temporary' | 'floating';
export type BranchRole = 'manager' | 'supervisor' | 'staff';

@Entity({ name: 'user_branch_assignments', schema: 'core' })
@Unique(['userId', 'branchId', 'assignmentType'])
export class UserBranchAssignment {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  @Index()
  @Column({ name: 'branch_id', type: 'uuid' })
  branchId: string;

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

  // Tipo de asignacion
  @Column({ name: 'assignment_type', type: 'varchar', length: 30, default: 'primary' })
  assignmentType: AssignmentType;

  // Rol en la sucursal
  @Column({ name: 'branch_role', type: 'varchar', length: 50, nullable: true })
  branchRole: BranchRole;

  // Permisos especificos
  @Column({ type: 'jsonb', default: [] })
  permissions: string[];

  // Vigencia (para asignaciones temporales)
  @Column({ name: 'valid_from', type: 'timestamptz', default: () => 'CURRENT_TIMESTAMP' })
  validFrom: Date;

  @Column({ name: 'valid_until', type: 'timestamptz', nullable: true })
  validUntil: Date;

  // Estado
  @Index()
  @Column({ name: 'is_active', type: 'boolean', default: true })
  isActive: boolean;

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

  @Column({ name: 'created_by', type: 'uuid', nullable: true })
  createdBy: string;

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

  // Relaciones
  @ManyToOne(() => Branch, (branch) => branch.userAssignments, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'branch_id' })
  branch: Branch;
}
