export const DATABASE_ID = "isletmem";

export const BUCKETS = {
  tenantLogos: "tenant-logos",
  entityAttachments: "entity-attachments",
} as const;

export const TABLES = {
  tenantSettings: "tenant_settings",
  customers: "customers",
  services: "services",
  software: "software",
  customerSoftware: "customer_software",
  calendarEvents: "calendar_events",
  tasks: "tasks",
  financeEntries: "finance_entries",
  invoices: "invoices",
  invoiceItems: "invoice_items",
  auditLogs: "audit_logs",
  inviteLinks: "invite_links",
  bankAccounts: "bank_accounts",
  bankLoans: "bank_loans",
  loanInstallments: "loan_installments",
  creditCards: "credit_cards",
  creditCardStatements: "credit_card_statements",
  subscriptionPayments: "subscription_payments",
  savedCards: "saved_cards",
  leads: "leads",
  leadActivities: "lead_activities",
  passwordResets: "password_resets",
  attachments: "attachments",
} as const;

export type TableId = (typeof TABLES)[keyof typeof TABLES];

export type SystemRow = {
  $id: string;
  $createdAt: string;
  $updatedAt: string;
  $permissions: string[];
  $databaseId?: string;
  $tableId?: string;
  $sequence?: number;
};

type Row = SystemRow;

export type TenantRole = "owner" | "admin" | "member";

export type TenantPlan = "free" | "pro";

export interface TenantSettings extends Row {
  tenantId: string;
  companyName: string;
  companyTaxId?: string;
  companyAddress?: string;
  companyEmail?: string;
  companyPhone?: string;
  logo?: string;
  defaultVatRate?: number;
  invoicePrefix?: string;
  invoiceCounter?: number;
  plan?: TenantPlan;
  planStartedAt?: string;
  planExpiresAt?: string;
  lastPaymentId?: string;
}

export type CustomerStatus = "active" | "passive";

export interface Customer extends Row {
  tenantId: string;
  createdBy: string;
  name: string;
  email?: string;
  phone?: string;
  taxId?: string;
  taxOffice?: string;
  website?: string;
  address?: string;
  notes?: string;
  status?: CustomerStatus;
}

export type BillingPeriod = "monthly" | "yearly" | "onetime";

export interface Service extends Row {
  tenantId: string;
  createdBy: string;
  customerId: string;
  name: string;
  description?: string;
  unitPrice: number;
  currency?: string;
  recurring?: boolean;
  billingPeriod?: BillingPeriod;
  assigneeIds?: string[];
}

export interface Software extends Row {
  tenantId: string;
  createdBy: string;
  name: string;
  version?: string;
  description?: string;
  defaultFee?: number;
}

export interface CustomerSoftware extends Row {
  tenantId: string;
  createdBy: string;
  customerId: string;
  softwareId: string;
  startDate?: string;
  endDate?: string;
  fee?: number;
  billingPeriod?: BillingPeriod;
  notes?: string;
}

export interface CalendarEvent extends Row {
  tenantId: string;
  createdBy: string;
  title: string;
  description?: string;
  start: string;
  end: string;
  allDay?: boolean;
  customerId?: string;
  leadId?: string;
  color?: string;
}

export type LeadStatus = "cold" | "warm" | "hot" | "converted" | "lost";
export type LeadSource = "website" | "social" | "referral" | "cold_call" | "event" | "other";
export type LeadActivityType = "note" | "call" | "meeting" | "email" | "status_change";

export interface Lead extends Row {
  tenantId: string;
  createdBy: string;
  name: string;
  contactName?: string;
  email?: string;
  phone?: string;
  source?: LeadSource;
  status?: LeadStatus;
  estimatedValue?: number;
  currency?: string;
  notes?: string;
  assigneeId?: string;
  lastContactAt?: string;
  nextFollowUpAt?: string;
  calendarEventId?: string;
  customerId?: string;
}

export interface LeadActivity extends Row {
  tenantId: string;
  createdBy: string;
  leadId: string;
  type: LeadActivityType;
  content: string;
  calendarEventId?: string;
  occurredAt?: string;
}

export type TaskStatus = "backlog" | "todo" | "in_progress" | "done";
export type TaskPriority = "low" | "medium" | "high" | "urgent";

export interface Task extends Row {
  tenantId: string;
  createdBy: string;
  title: string;
  description?: string;
  status?: TaskStatus;
  priority?: TaskPriority;
  dueDate?: string;
  assigneeId?: string;
  customerId?: string;
  order?: number;
}

export type FinanceType = "income" | "expense" | "debt" | "receivable";
export type PaymentMethod = "cash" | "transfer" | "card" | "check" | "other";

export interface FinanceEntry extends Row {
  tenantId: string;
  createdBy: string;
  type: FinanceType;
  amount: number;
  date: string;
  description?: string;
  customerId?: string;
  invoiceId?: string;
  paymentMethod?: PaymentMethod;
  bankAccountId?: string;
  scope?: "company" | "personal";
}

export type InvoiceStatus = "draft" | "sent" | "paid" | "overdue" | "cancelled";

export interface Invoice extends Row {
  tenantId: string;
  createdBy: string;
  number: string;
  customerId: string;
  issueDate: string;
  dueDate: string;
  status?: InvoiceStatus;
  subtotal?: number;
  vatTotal?: number;
  total?: number;
  notes?: string;
}

export interface InvoiceItem extends Row {
  tenantId: string;
  createdBy: string;
  invoiceId: string;
  description: string;
  quantity: number;
  unitPrice: number;
  vatRate?: number;
  lineTotal: number;
}

export type AuditAction = "create" | "update" | "delete";

export interface AuditLog extends Row {
  tenantId: string;
  userId: string;
  action: AuditAction;
  entityType: string;
  entityId: string;
  changes?: string;
  ipAddress?: string;
  userAgent?: string;
}

export type FinanceScope = "company" | "personal";

export interface BankAccount extends Row {
  tenantId: string;
  createdBy: string;
  bankName: string;
  accountName: string;
  iban?: string;
  openingBalance?: number;
  notes?: string;
  archived?: boolean;
  scope?: FinanceScope;
}

export type LoanType = "consumer" | "vehicle" | "housing" | "commercial" | "kmh" | "other";
export type LoanStatus = "active" | "closed" | "defaulted";

export interface BankLoan extends Row {
  tenantId: string;
  createdBy: string;
  bankAccountId?: string;
  bankName: string;
  loanName: string;
  loanType?: LoanType;
  principal: number;
  interestRate: number; // monthly nominal %
  termMonths: number;
  monthlyPayment?: number;
  startDate: string;
  paymentDay?: number;
  status?: LoanStatus;
  notes?: string;
  scope?: FinanceScope;
}

export interface LoanInstallment extends Row {
  tenantId: string;
  loanId: string;
  installmentNo: number;
  dueDate: string;
  amount: number;
  principalPart?: number;
  interestPart?: number;
  paid?: boolean;
  paidAt?: string;
  financeEntryId?: string;
}

export interface CreditCard extends Row {
  tenantId: string;
  createdBy: string;
  bankName: string;
  cardName: string;
  last4?: string;
  creditLimit?: number;
  statementDay?: number;
  dueDay?: number;
  interestRate?: number;
  bankAccountId?: string;
  archived?: boolean;
  notes?: string;
  scope?: FinanceScope;
}

export type StatementStatus = "pending" | "partial" | "paid" | "overdue";

export interface CreditCardStatement extends Row {
  tenantId: string;
  createdBy: string;
  cardId: string;
  period: string; // YYYY-MM
  statementDate: string;
  dueDate: string;
  totalDebt: number;
  minimumPayment?: number;
  paidAmount?: number;
  status?: StatementStatus;
  financeEntryId?: string;
  notes?: string;
}

export type SubscriptionStatus = "pending" | "success" | "failed" | "refunded";
export type SubscriptionProvider = "mock" | "shopier" | "polar";

export type CardBrand = "visa" | "mastercard" | "amex" | "troy" | "unknown";

export interface SavedCard extends Row {
  tenantId: string;
  createdBy: string;
  brand?: CardBrand;
  last4: string;
  expiryMonth: number;
  expiryYear: number;
  holderName?: string;
  providerToken?: string;
  provider?: SubscriptionProvider;
  isDefault?: boolean;
}

export interface SubscriptionPayment extends Row {
  tenantId: string;
  createdBy: string;
  orderId: string;
  plan: TenantPlan;
  amount: number;
  currency?: string;
  status?: SubscriptionStatus;
  provider?: SubscriptionProvider;
  providerPayload?: string;
  processedAt?: string;
}

export type InviteRole = "admin" | "member";
export type InviteStatus = "pending" | "accepted" | "cancelled" | "expired";

export interface InviteLink extends Row {
  tenantId: string;
  code: string;
  email: string;
  role?: InviteRole;
  status?: InviteStatus;
  invitedBy: string;
  expiresAt?: string;
  acceptedAt?: string;
  acceptedBy?: string;
}

export interface Attachment extends Row {
  tenantId: string;
  createdBy: string;
  entityType: string;
  entityId: string;
  fileId: string;
  name: string;
  size: number;
  mimeType?: string;
}
