import {
  Entity,
  Column,
  PrimaryColumn,
  ManyToOne,
  JoinColumn,
  CreateDateColumn,
} from 'typeorm';
import { User } from './user.entity';
import { Family } from './family.entity';

export enum FamilyRole {
  PARENT = 'parent',
  CAREGIVER = 'caregiver',
  VIEWER = 'viewer',
}

export interface FamilyPermissions {
  canAddChildren: boolean;
  canEditChildren: boolean;
  canLogActivities: boolean;
  canViewReports: boolean;
  canInviteMembers: boolean;
}

@Entity('family_members')
export class FamilyMember {
  @PrimaryColumn({ name: 'user_id', length: 20 })
  userId: string;

  @PrimaryColumn({ name: 'family_id', length: 20 })
  familyId: string;

  @Column({
    type: 'varchar',
    length: 20,
    enum: FamilyRole,
  })
  role: FamilyRole;

  @Column({
    type: 'jsonb',
    default: {
      canAddChildren: false,
      canEditChildren: false,
      canLogActivities: true,
      canViewReports: true,
    },
  })
  permissions: FamilyPermissions;

  @Column({ name: 'invited_by', length: 20, nullable: true })
  invitedBy?: string;

  @Column({
    name: 'access_granted_at',
    type: 'timestamp without time zone',
    nullable: true,
    default: () => 'CURRENT_TIMESTAMP',
  })
  accessGrantedAt: Date;

  @Column({
    name: 'access_expires_at',
    type: 'timestamp without time zone',
    nullable: true,
  })
  accessExpiresAt?: Date | null;

  @CreateDateColumn({ name: 'joined_at' })
  joinedAt: Date;

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

  @ManyToOne(() => Family, (family) => family.members, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'family_id' })
  family: Family;
}
