// ============================================================
// Mindavio — Shared Type Definitions
// ============================================================

export type Priority = "urgent" | "high" | "medium" | "low" | "none";

export type LeadStatus = "neu" | "kontaktiert" | "angebot" | "gewonnen" | "verloren";
export type LeadScore  = "cold" | "warm" | "hot";

export type Lead = {
  id: string;
  user_id: string;
  team_id?: string | null;
  assigned_to?: string | null;
  name: string;
  email?: string | null;
  phone?: string | null;
  company?: string | null;
  category: string;
  status: LeadStatus;
  score: LeadScore;
  source?: string | null;
  value?: number | null;
  notes?: string | null;
  created_at: string;
  updated_at: string;
};

export type LeadNote = {
  id: string;
  lead_id: string;
  user_id: string;
  team_id?: string | null;
  content: string;
  created_at: string;
  profiles?: { full_name: string; avatar_url: string | null } | null;
};

export type LeadActivity = {
  id: string;
  lead_id: string;
  user_id: string;
  team_id?: string | null;
  type: string;
  description: string;
  created_at: string;
  profiles?: { full_name: string; avatar_url: string | null } | null;
};

export type BusinessEntityType = "company" | "brand" | "project" | "portfolio";
export type InsightDataSourceType = "manual" | "csv" | "excel" | "json" | "api" | "integration" | "webhook";
export type InsightMetricValueType = "number" | "currency" | "percent" | "duration";
export type InsightMetricAggregation = "sum" | "avg" | "last" | "min" | "max";
export type InsightMetricDirection = "up" | "down" | "neutral";
export type InsightGoalStatus = "active" | "completed" | "paused" | "missed";
export type InsightRecommendationKind = "manual" | "why" | "action" | "risk" | "opportunity" | "breakout";
export type InsightRecommendationStatus = "open" | "converted" | "dismissed";

export interface BusinessEntity {
  id: string;
  user_id: string;
  team_id: string | null;
  name: string;
  entity_type: BusinessEntityType;
  description: string;
  color: string;
  linked_project_id: string | null;
  is_archived: boolean;
  created_at: string;
  updated_at: string;
}

export interface InsightDataSource {
  id: string;
  user_id: string;
  team_id: string | null;
  business_entity_id: string | null;
  provider: string;
  source_type: InsightDataSourceType;
  name: string;
  config: Record<string, unknown>;
  is_active: boolean;
  last_sync_at: string | null;
  created_at: string;
  updated_at: string;
}

export interface InsightMetricDefinition {
  id: string;
  user_id: string;
  team_id: string | null;
  business_entity_id: string | null;
  name: string;
  slug: string;
  category: string;
  value_type: InsightMetricValueType;
  unit: string;
  aggregation: InsightMetricAggregation;
  direction: InsightMetricDirection;
  color: string;
  sort_order: number;
  is_archived: boolean;
  created_at: string;
  updated_at: string;
}

export interface InsightMetricEntry {
  id: string;
  user_id: string;
  team_id: string | null;
  business_entity_id: string | null;
  metric_definition_id: string;
  data_source_id: string | null;
  period_start: string;
  period_end: string;
  value: number;
  dimensions: Record<string, unknown>;
  note: string;
  created_at: string;
  updated_at: string;
}

export interface InsightGoal {
  id: string;
  user_id: string;
  team_id: string | null;
  business_entity_id: string | null;
  metric_definition_id: string | null;
  name: string;
  target_value: number;
  current_value: number;
  period_start: string;
  period_end: string;
  status: InsightGoalStatus;
  created_at: string;
  updated_at: string;
}

export interface InsightRecommendation {
  id: string;
  user_id: string;
  team_id: string | null;
  business_entity_id: string | null;
  metric_definition_id: string | null;
  title: string;
  body: string;
  kind: InsightRecommendationKind;
  confidence: number | null;
  evidence: Record<string, unknown>;
  status: InsightRecommendationStatus;
  linked_task_id: string | null;
  created_at: string;
  updated_at: string;
}
export type TaskStatus = "todo" | "in_progress" | "done" | "cancelled";
export type RecurrencePattern = "none" | "daily" | "weekly" | "monthly";
export type ProjectHealth = "on_track" | "at_risk" | "stuck";
export type TaskReviewStatus =
  | "not_required"
  | "pending_review"
  | "changes_requested"
  | "approved";
export type ProjectApprovalStatus =
  | "not_required"
  | "pending_approval"
  | "changes_requested"
  | "approved";
export type EventResponseStatus = "pending" | "accepted" | "declined";
export type OrganizationRole = "owner" | "admin" | "member";
export type BillingPlan = "starter" | "growth" | "enterprise";
export type BillingCycle = "monthly" | "yearly";
export type SubscriptionStatus = "trialing" | "active" | "past_due" | "paused" | "cancelled";
export type BillingAdjustmentType =
  | "trial_extension_days"
  | "complimentary_period"
  | "seat_grant"
  | "price_override"
  | "discount_percent"
  | "discount_fixed"
  | "manual_status_override";
export type SeatStatus = "active" | "suspended";
export type AuthMethod = "password" | "magic_link" | "google" | "github" | "azure";
export type DeveloperAccessLevel = "read_only" | "read_write";
export type AutomationTriggerMode = "event" | "schedule";
export type AutomationScheduleFrequency = "daily" | "weekly";
export type AutomationTaskDeadlineState = "has_deadline" | "no_deadline" | "overdue";
export type IntegrationProvider =
  | "slack"
  | "google_calendar"
  | "gmail"
  | "google_drive"
  | "github"
  | "telegram"
  | "google_sheets"
  | "notion";
export type WebhookEventType =
  | "schedule.triggered"
  | "project.created"
  | "project.updated"
  | "project.deleted"
  | "task.created"
  | "task.updated"
  | "task.deleted"
  | "note.created"
  | "note.updated"
  | "note.deleted"
  | "lead.created"
  | "lead.updated"
  | "lead.deleted"
  | "event.created"
  | "event.updated"
  | "event.deleted";
export type AutomationActionType =
  | "send_slack"
  | "send_telegram"
  | "send_google_sheets"
  | "send_notion"
  | "create_gmail_draft"
  | "create_task"
  | "create_note"
  | "ai_create_task"
  | "ai_create_note";
export type AutomationRunStatus = "success" | "failed";

export interface AutomationRuleConditions {
  title_contains?: string | null;
  task_status_is?: TaskStatus | null;
  task_status_changed_to?: TaskStatus | null;
  task_priority_is?: Priority | null;
  project_health_is?: ProjectHealth | null;
  task_deadline_state?: AutomationTaskDeadlineState | null;
  task_tag_id?: string | null;
  project_id?: string | null;
  goal_id?: string | null;
  assignee_id?: string | null;
  reviewer_id?: string | null;
}

export interface AutomationActionConfig {
  connection_id?: string | null;
  task_title_template?: string | null;
  task_description_template?: string | null;
  assignee_id?: string | null;
  reviewer_id?: string | null;
  note_title_template?: string | null;
  note_content_template?: string | null;
  note_folder_id?: string | null;
  email_to_template?: string | null;
  email_subject_template?: string | null;
  email_body_template?: string | null;
  task_priority?: Priority | null;
  prompt_template?: string | null;
}

export interface AutomationStep {
  id: string;
  action_type: AutomationActionType;
  action_config: AutomationActionConfig;
}

export interface Profile {
  id: string;
  email: string;
  full_name: string;
  avatar_url: string | null;
  username?: string | null;
  created_at: string;
  updated_at: string;
}

export type TeamRole = "owner" | "admin" | "member" | "viewer";
export type PermissionLevel = "none" | "view" | "comment" | "edit" | "manage";
export type TeamResource =
  | "projects"
  | "tasks"
  | "notes"
  | "calendar"
  | "comments"
  | "members";

export interface Team {
  id: string;
  owner_id: string;
  name: string;
  slug: string;
  description: string;
  created_at: string;
  updated_at: string;
}

export interface TeamMember {
  team_id: string;
  user_id: string;
  role: TeamRole;
  title: string;
  joined_at: string;
  profile?: Profile;
}

export interface TeamInvitation {
  id: string;
  team_id: string;
  email: string;
  role: Exclude<TeamRole, "owner">;
  token: string;
  message: string;
  expires_at: string;
  sent_at: string | null;
  invited_by: string;
  status: "pending" | "accepted" | "revoked";
  created_at: string;
  updated_at: string;
}

export interface TeamRolePermission {
  team_id: string;
  role: TeamRole;
  resource: TeamResource;
  access_level: PermissionLevel;
  updated_at?: string;
}

export interface TeamAuditEntry {
  id: string;
  team_id: string;
  actor_id: string | null;
  action: string;
  entity_type:
    | "team"
    | "member"
    | "invite"
    | "project"
    | "task"
    | "note"
    | "event"
    | "comment";
  entity_id: string | null;
  title: string;
  details: Record<string, unknown>;
  created_at: string;
  actor?: Profile | null;
}

export interface Organization {
  id: string;
  owner_id: string;
  name: string;
  slug: string;
  description: string;
  created_at: string;
  updated_at: string;
}

export interface OrganizationMember {
  organization_id: string;
  user_id: string;
  role: OrganizationRole;
  title: string;
  seat_status: SeatStatus;
  counts_toward_seat: boolean;
  joined_at: string;
  profile?: Profile | null;
}

export interface OrganizationTeam {
  organization_id: string;
  team_id: string;
  linked_at: string;
  team?: Team | null;
}

export interface OrganizationBilling {
  organization_id: string;
  billing_email: string;
  billing_name: string;
  plan: BillingPlan;
  billing_cycle: BillingCycle;
  subscription_status: SubscriptionStatus;
  included_seats: number;
  purchased_seats: number;
  monthly_price_cents: number;
  trial_ends_at: string | null;
  renews_at: string | null;
  cancel_at: string | null;
  created_at: string;
  updated_at: string;
}

export interface OrganizationBillingAdjustment {
  id: string;
  organization_id: string;
  created_by: string;
  type: BillingAdjustmentType;
  amount: number | null;
  text_value: string | null;
  note: string;
  starts_at: string;
  ends_at: string | null;
  is_active: boolean;
  revoked_at: string | null;
  revoked_by: string | null;
  created_at: string;
  updated_at: string;
  actor?: Profile | null;
}

export interface OrganizationBillingEvent {
  id: string;
  organization_id: string;
  actor_id: string | null;
  action: string;
  title: string;
  details: Record<string, unknown>;
  created_at: string;
  actor?: Profile | null;
}

export interface EffectiveOrganizationBilling {
  base: OrganizationBilling | null;
  activeAdjustments: OrganizationBillingAdjustment[];
  effectiveStatus: SubscriptionStatus;
  effectiveMonthlyPriceCents: number;
  effectiveSeatCapacity: number;
  seatGrantCount: number;
  discountPercent: number;
  discountFixedCents: number;
  priceOverrideCents: number | null;
  complimentaryUntil: string | null;
  trialExtensionDays: number;
  effectiveRenewsAt: string | null;
  nextChargeAt: string | null;
  manualStatusOverride: SubscriptionStatus | null;
  isComplimentaryActive: boolean;
}

export type InvoiceDirection = "outgoing" | "incoming";
export type InvoiceDocumentType = "invoice" | "quote";
export type InvoiceStatus = "draft" | "ready" | "sent" | "received" | "paid" | "overdue" | "cancelled";
export type InvoiceSource = "manual" | "upload" | "shopify_pdf" | "email" | "internal";
export type InvoiceEventType =
  | "created"
  | "updated"
  | "status_changed"
  | "exported"
  | "send_prepared"
  | "marked_paid"
  | "attachment_added"
  | "attachment_removed";

export interface InvoiceCustomer {
  id: string;
  user_id: string;
  team_id: string | null;
  name: string;
  email: string;
  address: string;
  contact_person: string;
  vat_id: string;
  payment_terms_days: number;
  notes: string;
  created_at: string;
  updated_at: string;
}

export interface InvoiceFolder {
  id: string;
  user_id: string;
  team_id: string | null;
  name: string;
  slug: string;
  color: string;
  icon: string;
  sort_order: number;
  is_smart: boolean;
  created_at: string;
  updated_at: string;
}

export interface InvoiceItem {
  id: string;
  invoice_id: string;
  user_id: string;
  team_id: string | null;
  description: string;
  quantity: number;
  unit_price_cents: number;
  sort_order: number;
  created_at: string;
  updated_at: string;
}

export interface InvoiceEvent {
  id: string;
  invoice_id: string;
  user_id: string;
  team_id: string | null;
  event_type: InvoiceEventType;
  title: string;
  details: Record<string, unknown>;
  created_at: string;
}

export interface Invoice {
  id: string;
  user_id: string;
  team_id: string | null;
  customer_id: string | null;
  folder_id: string | null;
  document_type: InvoiceDocumentType;
  direction: InvoiceDirection;
  status: InvoiceStatus;
  source: InvoiceSource;
  invoice_number: string;
  title: string;
  counterparty_name: string;
  counterparty_email: string;
  counterparty_address: string;
  company_address: string;
  company_email: string;
  company_name: string;
  company_phone: string;
  company_vat_id: string;
  company_website: string;
  logo_url: string;
  accent_color: string;
  issue_date: string;
  due_date: string;
  notes: string;
  currency: string;
  tax_enabled: boolean;
  tax_rate: number;
  subtotal_cents: number;
  tax_cents: number;
  total_cents: number;
  sent_at: string | null;
  paid_at: string | null;
  cancelled_at: string | null;
  inbox_at: string | null;
  inbox_note: string;
  created_at: string;
  updated_at: string;
  customer?: InvoiceCustomer | null;
  folder?: InvoiceFolder | null;
  items?: InvoiceItem[];
  events?: InvoiceEvent[];
}

export interface OrganizationAuthPolicy {
  organization_id: string;
  allowed_auth_methods: AuthMethod[];
  allowed_email_domains: string[];
  auto_join_domains: string[];
  invite_only: boolean;
  require_domain_match: boolean;
  enforce_sso: boolean;
  created_at: string;
  updated_at: string;
}

export interface OrganizationWithContext extends Organization {
  members: OrganizationMember[];
  teams: OrganizationTeam[];
  assignableProfiles: Profile[];
  billing: OrganizationBilling | null;
  billingAdjustments: OrganizationBillingAdjustment[];
  billingEvents: OrganizationBillingEvent[];
  effectiveBilling: EffectiveOrganizationBilling | null;
  authPolicy: OrganizationAuthPolicy | null;
  invitations: OrganizationInvitation[];
  joinRequests: OrganizationJoinRequest[];
}

export interface OrganizationInvitation {
  id: string;
  organization_id: string;
  email: string;
  role: Exclude<OrganizationRole, "owner">;
  invited_by: string;
  token: string;
  message: string;
  status: "pending" | "accepted" | "declined" | "revoked";
  expires_at: string;
  sent_at: string | null;
  created_at: string;
  updated_at: string;
}

export interface OrganizationJoinRequest {
  id: string;
  organization_id: string;
  user_id: string;
  email: string;
  message: string;
  status: "pending" | "approved" | "declined" | "withdrawn";
  requested_at: string;
  reviewed_at: string | null;
  reviewed_by: string | null;
  created_at: string;
  updated_at: string;
  requester?: Profile | null;
  reviewer?: Profile | null;
}

export interface DeveloperApiToken {
  id: string;
  user_id: string;
  team_id: string | null;
  name: string;
  access_level: DeveloperAccessLevel;
  /** Per-section rights as stored (null = old token without per-section rights). */
  scopes?: Record<string, "none" | "read" | "write"> | null;
  /** What the token can really do per section (computed by the server). */
  effective_scopes?: Record<string, "none" | "read" | "write">;
  /** false while the database migration for per-section rights is missing. */
  scopes_supported?: boolean;
  token_prefix: string;
  last_used_at: string | null;
  expires_at: string | null;
  revoked_at: string | null;
  created_at: string;
  updated_at: string;
}

export interface WebhookEndpoint {
  id: string;
  user_id: string;
  team_id: string | null;
  name: string;
  url: string;
  event_types: WebhookEventType[];
  is_active: boolean;
  last_delivery_at: string | null;
  last_response_status: number | null;
  last_error: string | null;
  created_at: string;
  updated_at: string;
}

export interface WebhookDelivery {
  id: string;
  endpoint_id: string;
  user_id: string;
  team_id: string | null;
  event_type: WebhookEventType;
  delivery_id: string;
  payload: Record<string, unknown>;
  response_status: number | null;
  response_body: string | null;
  success: boolean;
  created_at: string;
}

export interface IntegrationConnection {
  id: string;
  user_id: string;
  team_id: string | null;
  provider: IntegrationProvider;
  name: string;
  config: Record<string, unknown>;
  event_types: WebhookEventType[];
  is_active: boolean;
  last_delivery_at: string | null;
  last_response_status: number | null;
  last_error: string | null;
  created_at: string;
  updated_at: string;
}

export interface AutomationRule {
  id: string;
  user_id: string;
  team_id: string | null;
  name: string;
  description: string;
  trigger_mode: AutomationTriggerMode;
  trigger_event: WebhookEventType;
  schedule_frequency: AutomationScheduleFrequency | null;
  schedule_time: string | null;
  schedule_day_of_week: number | null;
  schedule_timezone: string | null;
  conditions: AutomationRuleConditions;
  action_type: AutomationActionType;
  action_config: AutomationActionConfig;
  steps: AutomationStep[];
  is_active: boolean;
  last_run_at: string | null;
  last_scheduled_run_at: string | null;
  last_run_status: AutomationRunStatus | null;
  last_error: string | null;
  created_at: string;
  updated_at: string;
}

export interface AutomationRun {
  id: string;
  rule_id: string;
  user_id: string;
  team_id: string | null;
  trigger_mode: AutomationTriggerMode;
  trigger_event: WebhookEventType;
  payload: Record<string, unknown>;
  success: boolean;
  result_summary: string | null;
  error: string | null;
  created_at: string;
}

export interface GoogleCalendarConnectionConfig {
  calendarId: string | null;
  calendarSummary: string | null;
  connectedEmail: string | null;
}

export interface GmailConnectionConfig {
  connectedEmail: string | null;
}

export interface GoogleDriveConnectionConfig {
  connectedEmail: string | null;
}

export interface GitHubConnectionConfig {
  connectedLogin: string | null;
  connectedUrl: string | null;
  repoOwner: string | null;
  repoName: string | null;
  repoFullName: string | null;
}

export interface TelegramConnectionConfig {
  botUsername: string | null;
  chatId: string | null;
}

export interface GoogleSheetsConnectionConfig {
  webhookUrlMasked: string | null;
}

export interface NotionConnectionConfig {
  parentPageId: string | null;
}

export interface GitHubRepository {
  id: number;
  name: string;
  full_name: string;
  owner_login: string;
  html_url: string;
  private: boolean;
  default_branch: string | null;
}

export interface GmailMessageSummary {
  id: string;
  threadId: string | null;
  subject: string | null;
  from: string | null;
  date: string | null;
  snippet: string;
  internalDate: string | null;
  webUrl: string;
}

export interface GoogleDriveFileSummary {
  id: string;
  name: string;
  mimeType: string;
  webViewLink: string | null;
  iconLink: string | null;
  modifiedTime: string | null;
  owners: string[];
}

export interface GitHubIssueLink {
  id: string;
  connection_id: string;
  task_id: string;
  user_id: string;
  team_id: string | null;
  repo_owner: string;
  repo_name: string;
  issue_number: number;
  issue_title: string;
  issue_url: string;
  issue_state: string;
  created_at: string;
  updated_at: string;
}

export interface GoogleCalendarCalendar {
  id: string;
  summary: string;
  description: string | null;
  primary: boolean;
  accessRole: string | null;
  backgroundColor: string | null;
}

export interface IntegrationDelivery {
  id: string;
  connection_id: string;
  user_id: string;
  team_id: string | null;
  provider: IntegrationProvider;
  event_type: WebhookEventType;
  payload: Record<string, unknown>;
  response_status: number | null;
  response_body: string | null;
  success: boolean;
  created_at: string;
}

export interface CalendarFeedToken {
  id: string;
  user_id: string;
  team_id: string | null;
  name: string;
  token_prefix: string;
  is_active: boolean;
  last_accessed_at: string | null;
  created_at: string;
  updated_at: string;
}

export interface Comment {
  id: string;
  user_id: string;
  team_id: string | null;
  entity_type: "task" | "note";
  entity_id: string;
  body: string;
  mentioned_user_ids: string[];
  created_at: string;
  updated_at: string;
  author?: Profile | null;
  mentioned_users?: Profile[];
}

export interface Notification {
  id: string;
  user_id: string;
  actor_id: string | null;
  team_id: string | null;
  kind:
    | "mention"
    | "event_invite"
    | "task_review"
    | "project_approval"
    | "direct_message"
    | "direct_task_request"
    | "team_message"
    | "team_task_request"
    | "reminder_due";
  title: string;
  body: string;
  link: string;
  is_read: boolean;
  details: Record<string, unknown>;
  created_at: string;
  actor?: Profile | null;
}

export interface Project {
  id: string;
  user_id: string;
  team_id: string | null;
  goal_id: string | null;
  approver_id: string | null;
  approval_status: ProjectApprovalStatus;
  approval_requested_at: string | null;
  approved_at: string | null;
  approval_notes: string;
  name: string;
  color: string;
  icon: string;
  description: string;
  goal: string;
  health: "on_track" | "at_risk" | "stuck";
  sort_order: number;
  created_at: string;
  updated_at: string;
  approver?: Profile;
}

export type ProjectGuestRole = "view" | "comment" | "edit";

export interface ProjectGuest {
  project_id: string;
  user_id: string;
  role: ProjectGuestRole;
  invited_by: string | null;
  joined_at: string;
  profile?: Profile | null;
}

export interface ProjectGuestInvitation {
  id: string;
  project_id: string;
  email: string;
  role: ProjectGuestRole;
  invited_by: string;
  token: string;
  message: string;
  status: "pending" | "accepted" | "revoked";
  expires_at: string;
  sent_at: string | null;
  created_at: string;
  updated_at: string;
}

export interface ProjectTemplate {
  id: string;
  user_id: string;
  team_id: string | null;
  name: string;
  description: string;
  goal: string;
  color: string;
  icon: string;
  health: "on_track" | "at_risk" | "stuck";
  created_at: string;
  updated_at: string;
  tasks?: ProjectTemplateTask[];
}

export interface ProjectTemplateTask {
  id: string;
  template_id: string;
  user_id: string;
  team_id: string | null;
  title: string;
  description: string | null;
  priority: Priority;
  deadline_offset_days: number | null;
  sort_order: number;
  created_at: string;
  updated_at: string;
}

export interface ProjectLink {
  id: string;
  user_id: string;
  project_id: string;
  title: string;
  url: string;
  kind: string;
  sort_order: number;
  created_at: string;
  updated_at: string;
}

export interface ProjectActivity {
  id: string;
  user_id: string;
  project_id: string;
  entity_type: "project" | "task" | "note" | "link";
  entity_id: string | null;
  action: string;
  title: string;
  details: Record<string, unknown>;
  created_at: string;
}

export interface SavedView {
  id: string;
  user_id: string;
  team_id: string | null;
  scope: "tasks" | "notes" | "projects" | "documents" | "calendar";
  name: string;
  filters: Record<string, unknown>;
  is_favorite: boolean;
  created_at: string;
  updated_at: string;
}

export interface Attachment {
  id: string;
  user_id: string;
  team_id: string | null;
  project_id: string | null;
  entity_type: "project" | "task" | "note" | "chat_message" | "invoice";
  entity_id: string;
  file_name: string;
  storage_path: string;
  public_url: string;
  mime_type: string | null;
  size_bytes: number;
  created_at: string;
}

export interface Tag {
  id: string;
  user_id: string;
  team_id: string | null;
  name: string;
  color: string;
  created_at: string;
}

export interface Task {
  id: string;
  user_id: string;
  team_id: string | null;
  project_id: string | null;
  goal_id: string | null;
  assignee_id: string | null;
  reviewer_id: string | null;
  parent_task_id: string | null;
  bucket_id: string | null;
  title: string;
  description: string | null;
  priority: Priority;
  status: TaskStatus;
  review_status: TaskReviewStatus;
  review_requested_at: string | null;
  reviewed_at: string | null;
  review_notes: string;
  deadline: string | null;
  recurrence_pattern: RecurrencePattern;
  recurrence_interval: number;
  source_task_id: string | null;
  is_focus: boolean;
  focus_order: number;
  sort_order: number;
  completed_at: string | null;
  created_at: string;
  updated_at: string;
  // Joined
  tags?: Tag[];
  subtasks?: Task[];
  project?: Project;
  goal?: Goal;
  assignee?: Profile;
  reviewer?: Profile;
}

export interface TaskBucket {
  id: string;
  user_id: string;
  team_id: string | null;
  name: string;
  color: string;
  sort_order: number;
  created_at: string;
  updated_at: string;
}

export interface TaskTemplate {
  id: string;
  user_id: string;
  team_id: string | null;
  name: string;
  title: string;
  description: string;
  priority: Priority;
  status: TaskStatus;
  tag_ids: string[];
  recurrence_pattern: RecurrencePattern;
  recurrence_interval: number;
  sort_order: number;
  created_at: string;
  updated_at: string;
}

export interface NoteFolder {
  id: string;
  user_id: string;
  team_id: string | null;
  name: string;
  sort_order: number;
  created_at: string;
}

export interface Note {
  id: string;
  user_id: string;
  team_id: string | null;
  project_id: string | null;
  folder_id: string | null;
  linked_task_id: string | null;
  parent_note_id: string | null;
  cover_id: string | null;
  // Set when this note was created from a template — a note sourced from a
  // paid template can't be turned into a new template itself (prevents
  // reselling paid templates for free or cheaper).
  source_template_id: string | null;
  source_template_price_cents: number;
  title: string;
  content: Record<string, unknown>;
  is_pinned: boolean;
  pinned_order: number;
  sort_order: number;
  created_at: string;
  updated_at: string;
  // Joined
  tags?: Tag[];
  folder?: NoteFolder;
  project?: Project;
}

export type NoteRelationTargetType = "note" | "task" | "project";

export interface NoteRelation {
  id: string;
  user_id: string;
  team_id: string | null;
  source_note_id: string;
  target_note_id: string | null;
  target_task_id: string | null;
  target_project_id: string | null;
  created_at: string;
  target_type: NoteRelationTargetType;
  source_note?: Pick<Note, "id" | "title" | "project_id" | "updated_at"> | null;
  target_note?: Pick<Note, "id" | "title" | "project_id" | "updated_at"> | null;
  target_task?: Pick<Task, "id" | "title" | "status" | "priority" | "project_id"> | null;
  target_project?: Pick<Project, "id" | "name" | "icon" | "color"> | null;
}

export interface RelatedKnowledgeNote {
  id: string;
  title: string;
  project_id: string | null;
  updated_at: string;
  reasons: string[];
}

export type HabitFrequency = "daily" | "weekdays" | "weekends" | "custom";
export type Mood = "great" | "good" | "neutral" | "bad" | "terrible";
export type AchievementStatus =
  | "not_started"
  | "in_progress"
  | "completed"
  | "archived";
export type AchievementProgressSource =
  | "manual"
  | "completed_tasks_count"
  | "linked_tasks_completed_count";
export type ReminderStatus =
  | "scheduled"
  | "triggered"
  | "snoozed"
  | "done"
  | "cancelled";
export type ReminderRecurrenceRule = "none" | "daily" | "weekly" | "monthly" | "weekdays";
export type ReminderSourceType =
  | "manual"
  | "task"
  | "note"
  | "chat_message"
  | "achievement"
  | "project"
  | "journal"
  | "finance"
  | "calendar_event"
  | "invoice";

export interface Habit {
  id: string;
  user_id: string;
  name: string;
  icon: string;
  color: string;
  frequency: HabitFrequency;
  target_days: number[];
  sort_order: number;
  archived: boolean;
  created_at: string;
  updated_at: string;
}

export interface HabitCompletion {
  id: string;
  habit_id: string;
  user_id: string;
  completed_date: string;
  created_at: string;
}

export interface AchievementMilestone {
  id: string;
  achievement_id: string;
  title: string;
  description: string | null;
  milestone_value: number;
  unlocked_at: string | null;
  sort_order: number;
  created_at: string;
  completed_linked_task_count?: number;
  linked_task_count?: number;
  resolved_completed?: boolean;
  resolved_completion_source?: "manual" | "linked_tasks" | "progress" | null;
  task_links?: AchievementMilestoneTaskLink[];
}

export interface AchievementMilestoneTaskLink {
  milestone_id: string;
  task_id: string;
  created_at: string;
  task?: Pick<Task, "id" | "title" | "status"> | null;
}

export interface AchievementTaskLink {
  achievement_id: string;
  task_id: string;
  created_at: string;
  task?: Pick<Task, "id" | "title" | "status"> | null;
}

export interface AchievementProjectLink {
  achievement_id: string;
  project_id: string;
  created_at: string;
  project?: Pick<Project, "id" | "name" | "color" | "icon"> | null;
}

export interface AchievementRewardClaim {
  id: string;
  achievement_id: string;
  user_id: string;
  team_id: string | null;
  claimed_at: string;
  created_at: string;
}

export interface Achievement {
  id: string;
  user_id: string;
  team_id: string | null;
  title: string;
  description: string | null;
  category: string;
  icon: string;
  image_url: string | null;
  background_image_url: string | null;
  target_value: number;
  current_progress: number;
  status: AchievementStatus;
  progress_source: AchievementProgressSource;
  progress_metric_key: string | null;
  reward_title: string;
  reward_description: string | null;
  reward_image_url: string | null;
  reward_why: string | null;
  predefined: boolean;
  editable: boolean;
  deletable: boolean;
  starter_template_key: string | null;
  completed_at: string | null;
  sort_order: number;
  created_at: string;
  updated_at: string;
  milestones?: AchievementMilestone[];
  task_links?: AchievementTaskLink[];
  project_links?: AchievementProjectLink[];
  reward_claim?: AchievementRewardClaim | null;
  resolved_progress?: number;
  resolved_status?: AchievementStatus;
}

export interface Reminder {
  id: string;
  user_id: string;
  team_id: string | null;
  title: string;
  body: string | null;
  remind_at: string;
  status: ReminderStatus;
  recurrence_rule: ReminderRecurrenceRule;
  recurrence_days: number[];
  source_type: ReminderSourceType;
  source_id: string | null;
  source_title: string | null;
  source_url: string | null;
  snoozed_until: string | null;
  delivered_at: string | null;
  completed_at: string | null;
  created_at: string;
  updated_at: string;
}

export interface JournalTemplate {
  id: string;
  user_id: string;
  content: Record<string, unknown>;
  updated_at: string;
}

export interface JournalEntry {
  id: string;
  user_id: string;
  entry_date: string;
  title: string;
  content: Record<string, unknown>;
  mood: Mood | null;
  completed: boolean;
  created_at: string;
  updated_at: string;
}

export interface Affirmation {
  id: string;
  user_id: string;
  text: string;
  sort_order: number;
  created_at: string;
}

export interface Goal {
  id: string;
  user_id: string;
  team_id: string | null;
  title: string;
  description: string | null;
  target_date: string | null;
  progress: number; // 0-100
  color: string;
  icon: string;
  sort_order: number;
  completed: boolean;
  created_at: string;
  updated_at: string;
}

export type FinanceTransactionType = "income" | "expense";
export type FinanceTransactionStatus = "cleared" | "pending";
export type FinanceRecurringFrequency = "weekly" | "monthly" | "yearly";
export type FinanceCategoryType = "income" | "expense" | "both";

export interface FinanceTransaction {
  id: string;
  user_id: string;
  type: FinanceTransactionType;
  title: string;
  description: string;
  category: string;
  amount_cents: number;
  currency: string;
  transaction_date: string;
  status: FinanceTransactionStatus;
  created_at: string;
  updated_at: string;
}

export interface FinanceCategory {
  id: string;
  user_id: string;
  name: string;
  type: FinanceCategoryType;
  color: string;
  sort_order: number;
  created_at: string;
  updated_at: string;
}

export interface FinanceBudget {
  id: string;
  user_id: string;
  category: string;
  amount_cents: number;
  currency: string;
  month: string;
  created_at: string;
  updated_at: string;
}

export interface FinanceRecurringItem {
  id: string;
  user_id: string;
  type: FinanceTransactionType;
  title: string;
  category: string;
  amount_cents: number;
  currency: string;
  frequency: FinanceRecurringFrequency;
  next_due_date: string;
  is_active: boolean;
  created_at: string;
  updated_at: string;
}

export type CommunicationKind = "message" | "task_request";
export type DirectMessageStatus = "open" | "accepted" | "declined" | "done" | "archived";

export type ChatContactRequestStatus =
  | "pending"
  | "accepted"
  | "declined"
  | "cancelled";
export type ChatThreadType = "direct" | "group" | "channel";
export type ChatThreadRole = "owner" | "admin" | "member" | "viewer";
export type ChatNotificationLevel = "all" | "mentions" | "muted";
export type ChatPostingPermission = "members" | "admins";
export type ChatContextType =
  | "none"
  | "team"
  | "project"
  | "task"
  | "note"
  | "document"
  | "customer";
export type ChatMessageType = "text" | "system" | "decision" | "summary";

export interface ChatDirectoryProfile {
  id: string;
  username: string;
  full_name: string;
  avatar_url: string | null;
}

export interface ChatContactRequest {
  id: string;
  sender_id: string;
  recipient_id: string;
  message: string;
  status: ChatContactRequestStatus;
  created_at: string;
  updated_at: string;
  responded_at: string | null;
  sender?: Profile | null;
  recipient?: Profile | null;
}

export interface ChatContact {
  user_id: string;
  contact_user_id: string;
  source_request_id: string | null;
  favorite: boolean;
  created_at: string;
  contact?: Profile | null;
}

export interface ChatThreadMember {
  thread_id: string;
  user_id: string;
  role: ChatThreadRole;
  notification_level: ChatNotificationLevel;
  last_read_at: string | null;
  joined_at: string;
  user?: Profile | null;
}

export interface ChatMessageReaction {
  message_id: string;
  user_id: string;
  emoji: string;
  created_at: string;
}

export interface ChatMessageLink {
  id: string;
  message_id: string;
  actor_id: string;
  entity_type: "task" | "note" | "project";
  entity_id: string;
  created_at: string;
}

export interface ChatMessage {
  id: string;
  thread_id: string;
  sender_id: string;
  parent_message_id: string | null;
  message_type: ChatMessageType;
  body: string;
  mentioned_user_ids: string[];
  is_important: boolean;
  is_pinned: boolean;
  metadata: Record<string, unknown>;
  edited_at: string | null;
  deleted_at: string | null;
  created_at: string;
  updated_at: string;
  sender?: Profile | null;
  reactions?: ChatMessageReaction[];
  links?: ChatMessageLink[];
  attachments?: Attachment[];
}

export interface ChatThread {
  id: string;
  created_by: string;
  team_id: string | null;
  thread_type: ChatThreadType;
  context_type: ChatContextType;
  context_id: string | null;
  title: string;
  description: string;
  is_private: boolean;
  is_announcement: boolean;
  posting_permission: ChatPostingPermission;
  last_message_at: string | null;
  created_at: string;
  updated_at: string;
  participants?: ChatThreadMember[];
  last_message?: ChatMessage | null;
  unread?: boolean;
}

export interface DirectMessage {
  id: string;
  sender_id: string;
  recipient_email: string;
  recipient_id: string | null;
  kind: CommunicationKind;
  body: string;
  task_title: string;
  task_description: string;
  status: DirectMessageStatus;
  created_task_id: string | null;
  created_at: string;
  updated_at: string;
  sender?: Profile | null;
  recipient?: Profile | null;
}

export interface TeamMessage {
  id: string;
  team_id: string;
  sender_id: string;
  kind: CommunicationKind;
  body: string;
  task_title: string;
  task_description: string;
  created_task_id: string | null;
  created_at: string;
  updated_at: string;
  sender?: Profile | null;
}

export interface CalendarEvent {
  id: string;
  user_id: string;
  team_id: string | null;
  title: string;
  description: string | null;
  start_time: string;
  end_time: string;
  all_day: boolean;
  color: string | null;
  created_at: string;
  updated_at: string;
  participants?: EventParticipant[];
}

export interface EventParticipant {
  event_id: string;
  user_id: string;
  response_status: EventResponseStatus;
  created_at: string;
  profile?: Profile | null;
}

export interface MeetingTemplate {
  id: string;
  user_id: string;
  team_id: string | null;
  name: string;
  description: string;
  duration_minutes: number;
  all_day: boolean;
  color: string | null;
  created_at: string;
  updated_at: string;
  participants?: Profile[];
}
