// Types de base pour l'API
export interface User {
  id: string;
  username: string;
  slug?: string;
  email: string;
  first_name?: string;
  last_name?: string;
  avatar?: string;
  bio?: string;
  location?: string;
  birthdate?: string | null; // ISO8601 date string (nullable)
  gender?: string;
  username_changed_at?: string | null; // ISO8601 date string (nullable)
  role: string; // 'user' | 'admin' | 'super_admin'
  is_active: boolean;
  is_verified: boolean;
  is_admin: boolean;
  is_public: boolean;
  last_login_at?: string | null; // ISO8601 date string (nullable)
  created_at: string; // ISO8601 date string
  updated_at: string; // ISO8601 date string
  is_2fa_enabled?: boolean; // Legacy field, may not be in backend
}



export interface Message {
  id: string;
  conversation_id: string;
  sender_id: string;
  content: string;
  message_type: 'text' | 'image' | 'audio' | 'file';
  attachment_url?: string;
  created_at: string;
  updated_at: string;
  sender?: User;
}

export interface Conversation {
  id: string;
  name: string;
  type: 'direct' | 'group';
  creator_id: string;
  created_at: string;
  updated_at: string;
  participants?: User[];
  last_message?: Message;
  unread_count?: number;
}

export interface Track {
  id: string;
  creator_id: string; // Backend uses creator_id (not artist_id)
  file_id?: string; // nullable UUID
  title: string;
  artist: string; // Backend uses artist (string, not relation)
  album: string;
  duration: number; // seconds
  genre: string;
  year: number;
  file_path: string;
  file_size: number; // bytes
  format: string; // mp3, flac, wav, etc.
  bitrate: number; // kbps
  sample_rate: number; // Hz
  waveform_path?: string;
  cover_art_path?: string; // Backend uses cover_art_path (not cover_art_url)
  is_public: boolean;
  status: 'uploading' | 'processing' | 'completed' | 'failed';
  status_message?: string;
  stream_status: 'pending' | 'processing' | 'ready' | 'error';
  stream_manifest_url?: string;
  play_count: number;
  like_count: number;
  created_at: string; // ISO8601 date string
  updated_at: string; // ISO8601 date string
  // Relations (optionnelles)
  user?: User; // Backend relation User
}

export interface Session {
  id: string;
  user_id: string;
  // token is not exposed in JSON (json:"-")
  ip_address: string;
  user_agent: string;
  revoked_at?: string; // ISO8601 date string (nullable)
  expires_at: string; // ISO8601 date string
  created_at: string; // ISO8601 date string
}

export interface AuditLog {
  id: string;
  user_id?: string; // Backend uses *uuid.UUID (nullable)
  action: string;
  resource: string; // Backend uses resource (not resource_type)
  resource_id?: string; // Backend uses *uuid.UUID (nullable)
  metadata?: Record<string, any>; // Backend uses json.RawMessage (not details)
  ip_address?: string; // Backend uses string (nullable)
  user_agent?: string; // Backend uses string (nullable)
  timestamp: string; // ISO8601 date string (Backend uses timestamp, not created_at)
}

export interface AuditLogWithUser extends AuditLog {
  username?: string;
  user_role?: string;
}

// Types pour les statistiques d'audit
export interface AuditStats {
  action: string;
  resource: string;
  action_count: number;
  unique_users: number;
  unique_ips: number;
}

// Types pour les activités suspectes
export interface SuspiciousActivity {
  user_id?: string; // Backend uses *uuid.UUID (nullable)
  ip_address: string;
  action_count: number;
  unique_actions: number;
  risk_score: number;
}

// Types pour les requêtes d'authentification
// Note: These are kept for backward compatibility
// For exact backend DTO matching, use types from @/types/dto
export interface LoginRequest {
  email: string;
  password: string;
  remember_me?: boolean; // FE-TYPE-005: Added to match backend DTO
}

export interface RegisterRequest {
  username?: string; // FE-TYPE-005: Made optional to match backend DTO (omitempty)
  email: string;
  password: string;
  password_confirm?: string; // FE-TYPE-005: Added to match backend DTO
}

export interface AuthResult {
  access_token: string;
  refresh_token: string;
  expires_at: number;
  user_id: string;
  user: User;
  requires_2fa?: boolean; // FE-TYPE-005: Added to match backend LoginResponse DTO
}

export interface TokenClaims {
  user_id: string;
  exp: number;
  iat: number;
}

// Types pour les requêtes utilisateur
export interface CreateUserRequest {
  username: string;
  email: string;
  password: string;
}

export interface UpdateUserRequest {
  username?: string;
  email?: string;
  password?: string;
}

export interface UpdateProfileRequest {
  first_name?: string;
  last_name?: string;
  username?: string;
  bio?: string;
  location?: string;
  birthdate?: string; // Format: "YYYY-MM-DD"
  gender?: string; // 'Male' | 'Female' | 'Other' | 'Prefer not to say'
}

// Types pour les requêtes de messages
export interface SendMessageRequest {
  conversation_id: string;
  content: string;
  message_type?: 'text' | 'image' | 'audio' | 'file';
  attachment_url?: string;
}

export interface UpdateMessageRequest {
  content?: string;
}

// Types pour les requêtes de conversations
export interface CreateConversationRequest {
  name: string;
  type: 'direct' | 'group';
  participant_ids: string[];
}

export interface UpdateConversationRequest {
  name?: string;
}

// Types pour les requêtes de tracks
export interface UploadTrackRequest {
  title: string;
  artist_id: string;
  album_id?: string;
  genre: string;
  file: File;
  cover_art?: File;
}

export interface UpdateTrackRequest {
  title?: string;
  artist_id?: string;
  album_id?: string;
  genre?: string;
}

// Types pour la pagination
export interface PaginationParams {
  page?: number;
  limit?: number;
  cursor?: string;
}

export interface PaginationData {
  page: number;
  limit: number;
  total: number;
  total_pages: number;
  has_next: boolean;
  has_prev: boolean;
  next_cursor?: string;
  prev_cursor?: string;
}

// Types pour les réponses API
// Aligné avec FRONTEND_INTEGRATION.md
export interface ApiResponse<T> {
  success: boolean;
  data: T | null;
  error?: ApiError;
  message?: string;
}

// Types pour les erreurs API
// Aligné avec FRONTEND_INTEGRATION.md
export interface ApiError {
  code: number; // Code numérique (1000, 2000, etc.) ou code HTTP (429, 503, 502)
  message: string;
  details?: Array<{
    field: string;
    message: string;
    value?: string; // FE-TYPE-005: Added to match backend ValidationError DTO
  }>;
  request_id?: string;
  timestamp: string;
  context?: Record<string, any>;
  retry_after?: number; // Nombre de secondes avant de pouvoir réessayer (pour 429)
}

export interface ListResponse<T> {
  items: T[];
  pagination: PaginationData;
}

// Types pour les requêtes de liste
export interface ListUsersRequest extends PaginationParams {
  query?: string;
}

export interface ListMessagesRequest extends PaginationParams {
  conversation_id: string;
}

export interface ListConversationsRequest extends PaginationParams {
  query?: string;
}

export interface ListTracksRequest extends PaginationParams {
  artist?: string;
  genre?: string;
}

export interface SearchTracksRequest extends PaginationParams {
  query: string;
}

// Types pour les réponses de liste
export interface ListUsersResponse extends ListResponse<User> { }
export interface ListMessagesResponse extends ListResponse<Message> { }
export interface ListConversationsResponse extends ListResponse<Conversation> { }
export interface ListTracksResponse extends ListResponse<Track> { }
export interface SearchTracksResponse extends ListResponse<Track> { }

// Types pour les uploads
export interface UploadFileRequest {
  file: File;
  type: 'image' | 'audio' | 'document';
}

export interface UploadFileResponse {
  file_id: string;
  file_name: string;
  file_url: string;
  mime_type: string;
  size: number;
}

export interface FileMetadata {
  id: string;
  file_name: string;
  file_url: string;
  mime_type: string;
  size: number;
  uploader_id: string;
  uploaded_at: string;
}

// Types pour les notifications
export interface Notification {
  id: string;
  user_id: string;
  type: 'new_message' | 'track_uploaded' | 'user_mentioned' | 'system';
  content: string;
  read: boolean;
  created_at: string;
}

// Types pour les WebSockets
export interface WebSocketMessage {
  type:
  | 'message'
  | 'typing'
  | 'read_receipt'
  | 'user_joined'
  | 'user_left'
  | 'error';
  data: any;
  timestamp: string;
}

export interface TypingIndicator {
  user_id: string;
  conversation_id: string;
  is_typing: boolean;
}

export interface ReadReceipt {
  user_id: string;
  message_id: string;
  read_at: string;
}

// Types pour les erreurs
export interface ValidationError {
  field: string;
  message: string;
  code: string;
}

export interface FormError {
  message: string;
  errors?: ValidationError[];
}

// Types pour les états de l'application
export interface AppState {
  user: User | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  error: string | null;
}

export interface ChatState {
  conversations: Conversation[];
  activeConversation: string | null;
  messages: Record<string, Message[]>;
  typingUsers: Record<string, TypingIndicator[]>;
  unreadCounts: Record<string, number>;
}

export interface LibraryState {
  tracks: Track[];
  playlists: Playlist[];
  currentTrack: Track | null;
  isPlaying: boolean;
  volume: number;
  currentTime: number;
  duration: number;
}

export interface Playlist {
  id: string;
  user_id: string;
  title: string; // Backend uses 'title' in JSON, but column is 'name'
  description?: string;
  is_public: boolean;
  cover_url?: string;
  track_count: number;
  follower_count: number;
  created_at: string;
  updated_at: string;
  tracks?: Track[];
  // Relations (optionnelles)
  user?: User;
  playlist_tracks?: PlaylistTrack[];
  collaborators?: PlaylistCollaborator[];
}

export interface PlaylistTrack {
  id: string;
  playlist_id: string;
  track_id: string;
  position: number;
  added_by: string;
  added_at: string;
  track?: Track;
}

export interface PlaylistCollaborator {
  id: string;
  playlist_id: string;
  user_id: string;
  role: 'owner' | 'editor' | 'viewer';
  created_at: string;
  user?: User;
}

export interface PlaylistVersion {
  id: string;
  playlist_id: string;
  user_id: string;
  version: number;
  action: 'created' | 'updated' | 'restored';
  title: string;
  description?: string;
  is_public: boolean;
  cover_url?: string;
  tracks_snapshot?: string; // JSON string
  created_at: string;
}

// Types pour les thèmes
export interface Theme {
  name: string;
  colors: {
    primary: string;
    secondary: string;
    background: string;
    surface: string;
    text: string;
    textSecondary: string;
    border: string;
    error: string;
    warning: string;
    success: string;
  };
}

// Types pour la configuration
export interface AppConfig {
  apiUrl: string;
  wsUrl: string;
  uploadUrl: string;
  maxFileSize: number;
  supportedFormats: string[];
  features: {
    chat: boolean;
    library: boolean;
    streaming: boolean;
    uploads: boolean;
    notifications: boolean;
  };
}

// Types utilitaires
export type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
export type RequiredField<T, K extends keyof T> = T & Required<Pick<T, K>>;
export type DeepPartial<T> = {
  [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};

// Types pour les événements
export interface AppEvent {
  type: string;
  payload: any;
  timestamp: number;
}

export interface EventHandler<T = any> {
  (event: AppEvent & { payload: T }): void;
}

// Types pour les webhooks
export interface Webhook {
  id: string;
  user_id: string;
  url: string;
  events: string[]; // Array of event types
  active: boolean;
  // secret is not exposed in JSON (json:"omitempty" but should be hidden)
  created_at: string; // ISO8601 date string
  updated_at: string; // ISO8601 date string
}

export interface WebhookFailure {
  id: string;
  webhook_id: string;
  event: string;
  error: string;
  retries: number;
  created_at: string; // ISO8601 date string
}

// Types pour les paramètres admin
export interface AdminSettings {
  id: string;
  key: string;
  value: string;
  type: 'string' | 'int' | 'bool' | 'json';
  description?: string;
  category: string; // system, features, limits, etc.
  is_public: boolean;
  updated_by?: string;
  updated_at: string; // ISO8601 date string
}

// Types pour les analytics de lecture
export interface TrackPlay {
  id: string;
  track_id: string;
  user_id?: string; // nullable
  duration: number; // seconds played
  played_at: string; // ISO8601 date string
  device?: string;
  ip_address?: string;
  created_at: string; // ISO8601 date string
  updated_at: string; // ISO8601 date string
}

export interface PlaybackAnalytics {
  id: string;
  track_id: string;
  user_id: string;
  play_time: number; // seconds
  pause_count: number;
  seek_count: number;
  completion_rate: number; // percentage (0-100)
  started_at: string; // ISO8601 date string
  ended_at?: string; // ISO8601 date string (nullable)
  created_at: string; // ISO8601 date string
}

// Types pour les commentaires de tracks
export interface TrackComment {
  id: string;
  track_id: string;
  user_id: string;
  content: string;
  parent_id?: string; // nullable, for replies
  created_at: string; // ISO8601 date string
  updated_at: string; // ISO8601 date string
  user?: User;
  replies?: TrackComment[];
}

// Types pour les partages de tracks
export interface TrackShare {
  id: string;
  track_id: string;
  user_id: string;
  token: string;
  permissions: 'read' | 'write' | 'admin';
  expires_at?: string; // ISO8601 date string (nullable)
  created_at: string; // ISO8601 date string
}

// Types pour les likes de tracks
export interface TrackLike {
  id: string;
  track_id: string;
  user_id: string;
  created_at: string; // ISO8601 date string
}

// Types pour les versions de tracks
export interface TrackVersion {
  id: string;
  track_id: string;
  user_id: string;
  version: number;
  action: 'created' | 'updated' | 'restored';
  title?: string;
  artist?: string;
  album?: string;
  genre?: string;
  metadata_snapshot?: string; // JSON string
  created_at: string; // ISO8601 date string
}

// Types pour l'historique de tracks
export interface TrackHistory {
  id: string;
  track_id: string;
  user_id: string;
  action: string;
  details?: string; // JSON string
  created_at: string; // ISO8601 date string
}
