// ==========================================
// Enums
// ==========================================

export type UserRole = 'super_admin' | 'org_admin' | 'site_admin' | 'staff' | 'coach' | 'client';

export type CourtType = 'indoor' | 'outdoor' | 'covered';

export type CourtStatus = 'active' | 'maintenance' | 'inactive';

export type BookingStatus = 'pending' | 'confirmed' | 'cancelled' | 'completed' | 'no_show';

export type PaymentType = 'cash' | 'card' | 'transfer' | 'membership' | 'pending';

export type MembershipStatus = 'active' | 'expired' | 'cancelled' | 'suspended';

export type TournamentType = 'single_elimination' | 'double_elimination' | 'round_robin' | 'swiss';

export type TournamentStatus = 'draft' | 'registration_open' | 'registration_closed' | 'in_progress' | 'completed' | 'cancelled';

export type MatchStatus = 'scheduled' | 'in_progress' | 'completed' | 'cancelled' | 'walkover';

export type CashRegisterStatus = 'open' | 'closed';

// ==========================================
// Core Interfaces
// ==========================================

export interface Organization {
  id: string;
  name: string;
  slug: string;
  logo?: string;
  primaryColor?: string;
  secondaryColor?: string;
  email?: string;
  phone?: string;
  address?: string;
  taxId?: string;
  settings: OrganizationSettings;
  createdAt: Date;
  updatedAt: Date;
}

export interface OrganizationSettings {
  timezone: string;
  currency: string;
  dateFormat: string;
  timeFormat: '12h' | '24h';
  defaultBookingDuration: number; // in minutes
  cancellationPolicy: {
    allowCancellation: boolean;
    hoursBeforeBooking: number;
    refundPercentage: number;
  };
  bookingRules: {
    minAdvanceBooking: number; // hours
    maxAdvanceBooking: number; // days
    requirePayment: boolean;
  };
}

export interface Site {
  id: string;
  organizationId: string;
  name: string;
  slug: string;
  address: string;
  city: string;
  state?: string;
  country: string;
  postalCode?: string;
  latitude?: number;
  longitude?: number;
  phone?: string;
  email?: string;
  openingHours: WeeklySchedule;
  amenities: string[];
  images: string[];
  isActive: boolean;
  createdAt: Date;
  updatedAt: Date;
}

export interface WeeklySchedule {
  monday: DaySchedule;
  tuesday: DaySchedule;
  wednesday: DaySchedule;
  thursday: DaySchedule;
  friday: DaySchedule;
  saturday: DaySchedule;
  sunday: DaySchedule;
}

export interface DaySchedule {
  isOpen: boolean;
  openTime?: string; // HH:mm format
  closeTime?: string; // HH:mm format
  breaks?: TimeSlot[];
}

export interface TimeSlot {
  startTime: string; // HH:mm format
  endTime: string; // HH:mm format
}

export interface Court {
  id: string;
  siteId: string;
  name: string;
  type: CourtType;
  status: CourtStatus;
  description?: string;
  features: string[];
  hourlyRate: number;
  peakHourlyRate?: number;
  peakHours?: TimeSlot[];
  images: string[];
  position?: number; // for ordering
  createdAt: Date;
  updatedAt: Date;
}

// ==========================================
// User & Client Interfaces
// ==========================================

export interface User {
  id: string;
  email: string;
  passwordHash?: string;
  firstName: string;
  lastName: string;
  phone?: string;
  avatar?: string;
  role: UserRole;
  organizationId?: string;
  siteIds: string[]; // sites user has access to
  permissions: string[];
  isActive: boolean;
  emailVerified: boolean;
  lastLoginAt?: Date;
  createdAt: Date;
  updatedAt: Date;
}

export interface Client {
  id: string;
  userId?: string; // linked user account (optional)
  organizationId: string;
  firstName: string;
  lastName: string;
  email: string;
  phone?: string;
  dateOfBirth?: Date;
  gender?: 'male' | 'female' | 'other' | 'prefer_not_to_say';
  avatar?: string;
  address?: string;
  city?: string;
  postalCode?: string;
  country?: string;
  notes?: string;
  tags: string[];
  preferredSiteId?: string;
  skillLevel?: 'beginner' | 'intermediate' | 'advanced' | 'professional';
  emergencyContact?: EmergencyContact;
  marketingConsent: boolean;
  isActive: boolean;
  createdAt: Date;
  updatedAt: Date;
}

export interface EmergencyContact {
  name: string;
  relationship: string;
  phone: string;
}

// ==========================================
// Booking Interfaces
// ==========================================

export interface Booking {
  id: string;
  courtId: string;
  siteId: string;
  organizationId: string;
  clientId: string;
  createdByUserId?: string;
  startTime: Date;
  endTime: Date;
  duration: number; // in minutes
  status: BookingStatus;
  paymentType: PaymentType;
  paymentStatus: 'pending' | 'paid' | 'refunded' | 'partial';
  amount: number;
  paidAmount: number;
  currency: string;
  participants: BookingParticipant[];
  notes?: string;
  internalNotes?: string;
  isRecurring: boolean;
  recurringId?: string;
  cancellationReason?: string;
  cancelledAt?: Date;
  cancelledByUserId?: string;
  checkInAt?: Date;
  checkOutAt?: Date;
  createdAt: Date;
  updatedAt: Date;
}

export interface BookingParticipant {
  clientId?: string;
  name: string;
  email?: string;
  phone?: string;
  isPayer: boolean;
}

export interface RecurringBooking {
  id: string;
  courtId: string;
  siteId: string;
  organizationId: string;
  clientId: string;
  createdByUserId?: string;
  dayOfWeek: number; // 0-6 (Sunday-Saturday)
  startTime: string; // HH:mm format
  endTime: string; // HH:mm format
  startDate: Date;
  endDate?: Date;
  isActive: boolean;
  createdAt: Date;
  updatedAt: Date;
}

// ==========================================
// Membership Interfaces
// ==========================================

export interface MembershipPlan {
  id: string;
  organizationId: string;
  siteIds: string[]; // applicable sites
  name: string;
  description?: string;
  durationMonths: number;
  price: number;
  currency: string;
  benefits: MembershipBenefit[];
  bookingDiscount?: number; // percentage
  maxActiveBookings?: number;
  priorityBooking: boolean;
  guestPasses?: number;
  isActive: boolean;
  createdAt: Date;
  updatedAt: Date;
}

export interface MembershipBenefit {
  type: 'discount' | 'free_hours' | 'priority' | 'guest_pass' | 'product_discount' | 'custom';
  description: string;
  value?: number;
  conditions?: string;
}

export interface Membership {
  id: string;
  clientId: string;
  planId: string;
  organizationId: string;
  startDate: Date;
  endDate: Date;
  status: MembershipStatus;
  autoRenew: boolean;
  paymentMethod?: string;
  remainingGuestPasses: number;
  usedHours: number;
  notes?: string;
  suspendedAt?: Date;
  suspensionReason?: string;
  cancelledAt?: Date;
  cancellationReason?: string;
  createdAt: Date;
  updatedAt: Date;
}

// ==========================================
// Product & Sales Interfaces
// ==========================================

export interface ProductCategory {
  id: string;
  organizationId: string;
  name: string;
  description?: string;
  parentId?: string;
  position: number;
  isActive: boolean;
  createdAt: Date;
  updatedAt: Date;
}

export interface Product {
  id: string;
  organizationId: string;
  siteIds: string[]; // available at these sites
  categoryId?: string;
  name: string;
  description?: string;
  sku?: string;
  barcode?: string;
  price: number;
  cost?: number;
  currency: string;
  taxRate: number;
  trackInventory: boolean;
  images: string[];
  isActive: boolean;
  createdAt: Date;
  updatedAt: Date;
}

export interface ProductInventory {
  id: string;
  productId: string;
  siteId: string;
  quantity: number;
  minQuantity?: number;
  location?: string;
  updatedAt: Date;
}

export interface Sale {
  id: string;
  siteId: string;
  organizationId: string;
  clientId?: string;
  userId: string; // staff who made the sale
  cashRegisterId?: string;
  items: SaleItem[];
  subtotal: number;
  taxAmount: number;
  discountAmount: number;
  total: number;
  currency: string;
  paymentType: PaymentType;
  paymentReference?: string;
  notes?: string;
  voidedAt?: Date;
  voidedByUserId?: string;
  voidReason?: string;
  createdAt: Date;
  updatedAt: Date;
}

export interface SaleItem {
  productId?: string;
  bookingId?: string;
  membershipId?: string;
  description: string;
  quantity: number;
  unitPrice: number;
  taxRate: number;
  discountAmount: number;
  total: number;
}

export interface CashRegister {
  id: string;
  siteId: string;
  name: string;
  status: CashRegisterStatus;
  openedAt?: Date;
  openedByUserId?: string;
  openingBalance?: number;
  closedAt?: Date;
  closedByUserId?: string;
  closingBalance?: number;
  expectedBalance?: number;
  notes?: string;
  createdAt: Date;
  updatedAt: Date;
}

// ==========================================
// Tournament Interfaces
// ==========================================

export interface Tournament {
  id: string;
  siteId: string;
  organizationId: string;
  name: string;
  description?: string;
  type: TournamentType;
  status: TournamentStatus;
  startDate: Date;
  endDate: Date;
  registrationStartDate: Date;
  registrationEndDate: Date;
  maxTeams: number;
  minTeams: number;
  teamSize: number; // players per team (1 for singles, 2 for doubles)
  entryFee: number;
  currency: string;
  prizePool?: number;
  prizes?: TournamentPrize[];
  rules?: string;
  courtIds: string[];
  categories: TournamentCategory[];
  images: string[];
  isPublic: boolean;
  createdAt: Date;
  updatedAt: Date;
}

export interface TournamentCategory {
  id: string;
  name: string;
  description?: string;
  minSkillLevel?: string;
  maxSkillLevel?: string;
  minAge?: number;
  maxAge?: number;
  gender?: 'male' | 'female' | 'mixed' | 'any';
}

export interface TournamentPrize {
  position: number;
  description: string;
  amount?: number;
  currency?: string;
}

export interface TournamentTeam {
  id: string;
  tournamentId: string;
  categoryId: string;
  name: string;
  players: TournamentPlayer[];
  seed?: number;
  status: 'registered' | 'confirmed' | 'withdrawn' | 'disqualified';
  paidAt?: Date;
  notes?: string;
  createdAt: Date;
  updatedAt: Date;
}

export interface TournamentPlayer {
  clientId: string;
  firstName: string;
  lastName: string;
  email?: string;
  phone?: string;
  isCaptain: boolean;
}

export interface TournamentMatch {
  id: string;
  tournamentId: string;
  categoryId: string;
  round: number;
  matchNumber: number;
  courtId?: string;
  scheduledAt?: Date;
  team1Id?: string;
  team2Id?: string;
  winnerId?: string;
  score?: MatchScore;
  status: MatchStatus;
  notes?: string;
  createdAt: Date;
  updatedAt: Date;
}

export interface MatchScore {
  sets: SetScore[];
  winner: 'team1' | 'team2';
  duration?: number; // in minutes
}

export interface SetScore {
  team1Score: number;
  team2Score: number;
  tiebreak?: TiebreakScore;
}

export interface TiebreakScore {
  team1Score: number;
  team2Score: number;
}

// ==========================================
// Utility Types
// ==========================================

export type WithTimestamps<T> = T & {
  createdAt: Date;
  updatedAt: Date;
};

export type CreateInput<T> = Omit<T, 'id' | 'createdAt' | 'updatedAt'>;

export type UpdateInput<T> = Partial<Omit<T, 'id' | 'createdAt' | 'updatedAt'>>;

export type PaginationParams = {
  page?: number;
  limit?: number;
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
};

export type PaginatedResponse<T> = {
  data: T[];
  total: number;
  page: number;
  limit: number;
  totalPages: number;
};

export type ApiResponse<T> = {
  success: boolean;
  data?: T;
  error?: {
    code: string;
    message: string;
    details?: Record<string, unknown>;
  };
};
