1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
package main

import (
	"database/sql"
	"fmt"
	"log"
	"strings"
	"time"
	"unicode"

	"golang.org/x/text/runes"
	"golang.org/x/text/transform"
	"golang.org/x/text/unicode/norm"
)

// SQL migrations embedded as constants
const migration001 = `-- Initial schema for timetrack database
-- Creates schema_version tracking, clients, and time_entries tables

CREATE TABLE IF NOT EXISTS schema_version (
  version INTEGER PRIMARY KEY,
  applied_at INTEGER NOT NULL  -- Unix timestamp
);

CREATE TABLE IF NOT EXISTS clients (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL UNIQUE,
  target_hours REAL NOT NULL DEFAULT 40.0
);

CREATE TABLE IF NOT EXISTS time_entries (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  client_id INTEGER NOT NULL,
  start_time INTEGER NOT NULL,   -- Unix timestamp
  end_time INTEGER,               -- Unix timestamp, NULL = in progress
  FOREIGN KEY (client_id) REFERENCES clients(id),
  CHECK (end_time IS NULL OR end_time > start_time)
);

CREATE INDEX IF NOT EXISTS idx_time_entries_client_start
  ON time_entries(client_id, start_time);
`

const migration002 = `-- Add archived column to clients table
ALTER TABLE clients ADD COLUMN archived INTEGER NOT NULL DEFAULT 0;
CREATE INDEX IF NOT EXISTS idx_clients_archived ON clients(archived);
`

const migration003 = `-- Add archived_at timestamp to clients table
ALTER TABLE clients ADD COLUMN archived_at INTEGER;
CREATE INDEX IF NOT EXISTS idx_clients_archived_at ON clients(archived_at);
`

const migration004 = `-- Add comment column to time_entries table
ALTER TABLE time_entries ADD COLUMN comment TEXT NOT NULL DEFAULT '';
`

const migration005 = `-- Add invoicing support
-- Create invoices table (immutable once sent)
CREATE TABLE IF NOT EXISTS invoices (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  client_id INTEGER NOT NULL,
  invoice_number TEXT NOT NULL UNIQUE,
  created_at INTEGER NOT NULL,
  sent_at INTEGER,
  paid_at INTEGER,
  total_hours REAL NOT NULL,
  hourly_rate REAL,
  total_amount REAL,
  currency TEXT DEFAULT 'EUR',
  notes TEXT,
  status TEXT DEFAULT 'draft',
  FOREIGN KEY (client_id) REFERENCES clients(id)
);

-- Create invoice line items table (immutable snapshot of time entries)
CREATE TABLE IF NOT EXISTS invoice_line_items (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  invoice_id INTEGER NOT NULL,
  date TEXT NOT NULL,
  start_time INTEGER NOT NULL,
  end_time INTEGER,
  hours REAL NOT NULL,
  description TEXT,
  source_entry_id INTEGER,
  FOREIGN KEY (invoice_id) REFERENCES invoices(id) ON DELETE CASCADE,
  FOREIGN KEY (source_entry_id) REFERENCES time_entries(id) ON DELETE SET NULL
);

-- Add invoice_id to time_entries for tracking
ALTER TABLE time_entries ADD COLUMN invoice_id INTEGER REFERENCES invoices(id) ON DELETE SET NULL;

-- Create indexes for performance
CREATE INDEX IF NOT EXISTS idx_invoices_client ON invoices(client_id);
CREATE INDEX IF NOT EXISTS idx_invoices_number ON invoices(invoice_number);
CREATE INDEX IF NOT EXISTS idx_invoice_line_items_invoice ON invoice_line_items(invoice_id);
CREATE INDEX IF NOT EXISTS idx_time_entries_invoice ON time_entries(invoice_id);
`

const migration006 = `-- Add shortcode column to clients table for invoice prefixes
-- Shortcode is used to create client-specific invoice numbers (e.g., NP-2025-001)
-- Shortcodes must be unique and non-empty (enforced by unique index)
ALTER TABLE clients ADD COLUMN shortcode TEXT NOT NULL DEFAULT '';

-- Create unique index on non-empty shortcodes to prevent duplicates
-- Note: Empty strings ('') are allowed during migration for backward compatibility
CREATE UNIQUE INDEX idx_clients_shortcode ON clients(shortcode) WHERE shortcode != '';
`

const migration007 = `-- Add milestones support
-- Milestones are markers that appear in the time entry list at specific timestamps
-- They show cumulative hours and help track project phases
CREATE TABLE IF NOT EXISTS milestones (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  client_id INTEGER NOT NULL,
  name TEXT NOT NULL,
  timestamp INTEGER NOT NULL,
  FOREIGN KEY (client_id) REFERENCES clients(id) ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS idx_milestones_client_timestamp 
  ON milestones(client_id, timestamp);
`

const migration008 = `-- Add UI state persistence as key-value store
-- Stores UI state like selected client ID and scroll positions
CREATE TABLE IF NOT EXISTS ui_state (
  key TEXT PRIMARY KEY,
  value TEXT NOT NULL
);
`

// InitDB opens or creates the SQLite database at the given path,
// configures SQLite pragmas, and runs any pending migrations.
func InitDB(dbPath string) (*sql.DB, error) {
	// Pragmas travel in the DSN so they apply to every pooled connection:
	// busy_timeout (a writer waits for the lock instead of failing with
	// SQLITE_BUSY), foreign-key enforcement (off by default in SQLite), and WAL so readers do not block the writer. A post-open
	// db.Exec("PRAGMA …") would only configure whichever single pooled
	// connection ran it, leaving the others at SQLite's defaults.
	db, err := sql.Open("sqlite",
		"file:"+dbPath+"?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=foreign_keys(on)")
	if err != nil {
		return nil, fmt.Errorf("failed to open database: %w", err)
	}

	// Run migrations
	if err := runMigrations(db); err != nil {
		db.Close()
		return nil, fmt.Errorf("migration failed: %w", err)
	}

	// Seed with test data if database is empty
	if err := seedTestDataIfEmpty(db); err != nil {
		db.Close()
		return nil, fmt.Errorf("failed to seed test data: %w", err)
	}

	return db, nil
}

// runMigrations applies any pending database migrations.
// Migrations are applied in order based on their version number.
func runMigrations(db *sql.DB) error {
	// Define migrations as version number and SQL content
	migrations := []struct {
		version int
		sql     string
	}{
		{1, migration001},
		{2, migration002},
		{3, migration003},
		{4, migration004},
		{5, migration005},
		{6, migration006},
		{7, migration007},
		{8, migration008},
	}

	for _, migration := range migrations {
		// Check if this migration has already been applied
		var exists int
		err := db.QueryRow("SELECT COUNT(*) FROM schema_version WHERE version = ?", migration.version).Scan(&exists)
		if err != nil {
			// schema_version table doesn't exist yet, which is fine for first migration
			if migration.version != 1 {
				return fmt.Errorf("failed to check migration status: %w", err)
			}
		}

		if exists > 0 {
			continue // Migration already applied
		}

		// Execute migration in a transaction
		tx, err := db.Begin()
		if err != nil {
			return fmt.Errorf("failed to begin transaction for migration %d: %w", migration.version, err)
		}

		if _, err := tx.Exec(migration.sql); err != nil {
			tx.Rollback()
			return fmt.Errorf("failed to execute migration %d: %w", migration.version, err)
		}

		// Record that this migration has been applied
		if _, err := tx.Exec("INSERT INTO schema_version (version, applied_at) VALUES (?, ?)",
			migration.version, time.Now().Unix()); err != nil {
			tx.Rollback()
			return fmt.Errorf("failed to record migration %d: %w", migration.version, err)
		}

		if err := tx.Commit(); err != nil {
			return fmt.Errorf("failed to commit migration %d: %w", migration.version, err)
		}

		log.Printf("Applied migration %d", migration.version)
		fmt.Printf("✓ Applied migration %d\n", migration.version)
	}

	return nil
}

// LoadClients loads all clients and their time entries from the database.
func LoadClients(db *sql.DB) ([]Client, error) {
	// Query all clients (only non-archived ones)
	rows, err := db.Query(`
		SELECT c.id, c.name, c.shortcode, c.target_hours, c.archived, c.archived_at
		FROM clients c
		LEFT JOIN (
			SELECT client_id, MAX(start_time) AS last_activity
			FROM time_entries
			GROUP BY client_id
		) t ON c.id = t.client_id
		WHERE c.archived = 0
		ORDER BY t.last_activity DESC NULLS LAST, c.name
	`)
	if err != nil {
		return nil, fmt.Errorf("failed to query clients: %w", err)
	}
	defer rows.Close()

	var clients []Client
	for rows.Next() {
		var client Client
		var archivedInt int
		if err := rows.Scan(&client.ID, &client.Name, &client.Shortcode, &client.TargetHours, &archivedInt, &client.ArchivedAt); err != nil {
			return nil, fmt.Errorf("failed to scan client: %w", err)
		}
		client.Archived = (archivedInt != 0)

		// Load display items (entries + milestones) for this client
		displayItems, err := LoadClientDisplayItems(db, client.ID)
		if err != nil {
			return nil, fmt.Errorf("failed to load display items for client %s: %w", client.Name, err)
		}
		client.DisplayItems = displayItems

		clients = append(clients, client)
	}

	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("error iterating clients: %w", err)
	}

	return clients, nil
}

// loadTimeEntries loads all time entries for a specific client.
func loadTimeEntries(db *sql.DB, clientID int64) ([]TimeEntry, error) {
	rows, err := db.Query(`
		SELECT te.id, te.client_id, te.start_time, te.end_time, te.comment, te.invoice_id, inv.invoice_number
		FROM time_entries te
		LEFT JOIN invoices inv ON te.invoice_id = inv.id
		WHERE te.client_id = ?
		ORDER BY te.start_time
	`, clientID)
	if err != nil {
		return nil, fmt.Errorf("failed to query time entries: %w", err)
	}
	defer rows.Close()

	var entries []TimeEntry
	for rows.Next() {
		var entry TimeEntry

		if err := rows.Scan(&entry.ID, &entry.ClientID, &entry.StartTime, &entry.EndTime, &entry.Comment, &entry.InvoiceID, &entry.InvoiceNumber); err != nil {
			return nil, fmt.Errorf("failed to scan time entry: %w", err)
		}

		entries = append(entries, entry)
	}

	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("error iterating time entries: %w", err)
	}

	// Populate display indices (1-based)
	for i := range entries {
		entries[i].Index = i + 1
	}

	return entries, nil
}

// seedTestDataIfEmpty seeds the database with test data if the clients table is empty.
func seedTestDataIfEmpty(db *sql.DB) error {
	var count int
	if err := db.QueryRow("SELECT COUNT(*) FROM clients").Scan(&count); err != nil {
		return fmt.Errorf("failed to check if clients table is empty: %w", err)
	}

	if count > 0 {
		return nil // Data already exists
	}

	log.Println("Seeding database with test data...")

	// Helper to parse date+time into unix timestamp
	parseDateTime := func(date, timeStr string) int64 {
		layout := "2006-01-02 15:04"
		t, err := time.Parse(layout, date+" "+timeStr)
		if err != nil {
			log.Fatalf("Failed to parse date/time: %v", err)
		}
		return t.Unix()
	}

	tx, err := db.Begin()
	if err != nil {
		return fmt.Errorf("failed to begin transaction: %w", err)
	}

	// Insert test clients
	clients := []struct {
		name        string
		shortcode   string
		targetHours float64
		entries     []struct {
			date  string
			start string
			end   string
		}
	}{
		{
			name:        "Client1",
			shortcode:   "C1",
			targetHours: 40.0,
			entries: []struct {
				date  string
				start string
				end   string
			}{
				{"2025-06-04", "19:00", "21:00"},
				{"2025-06-05", "13:30", "18:00"},
				{"2025-09-05", "10:00", "18:00"},
			},
		},
		{
			name:        "Client2",
			shortcode:   "C2",
			targetHours: 40.0,
			entries: []struct {
				date  string
				start string
				end   string
			}{
				{"2025-09-06", "10:00", "18:00"},
				{"2025-09-07", "10:00", "18:00"},
				{"2025-09-09", "10:00", "12:00"},
			},
		},
		{
			name:        "Client3",
			shortcode:   "C3",
			targetHours: 40.0,
			entries: []struct {
				date  string
				start string
				end   string
			}{
				{"2025-09-09", "16:00", "18:00"},
				{"2025-09-10", "18:00", "21:00"},
				{"2025-09-11", "10:00", "18:00"},
			},
		},
	}

	for _, client := range clients {
		result, err := tx.Exec("INSERT INTO clients (name, shortcode, target_hours) VALUES (?, ?, ?)",
			client.name, client.shortcode, client.targetHours)
		if err != nil {
			tx.Rollback()
			return fmt.Errorf("failed to insert client %s: %w", client.name, err)
		}

		clientID, err := result.LastInsertId()
		if err != nil {
			tx.Rollback()
			return fmt.Errorf("failed to get client ID: %w", err)
		}

		for _, entry := range client.entries {
			startTime := parseDateTime(entry.date, entry.start)
			endTime := parseDateTime(entry.date, entry.end)

			_, err := tx.Exec("INSERT INTO time_entries (client_id, start_time, end_time) VALUES (?, ?, ?)",
				clientID, startTime, endTime)
			if err != nil {
				tx.Rollback()
				return fmt.Errorf("failed to insert time entry: %w", err)
			}
		}
	}

	if err := tx.Commit(); err != nil {
		return fmt.Errorf("failed to commit seed data: %w", err)
	}

	log.Println("Test data seeded successfully")
	return nil
}

// GetRunningEntry finds the currently running time entry for a client (end_time is NULL).
// Returns nil if no running entry exists.
func GetRunningEntry(db *sql.DB, clientID int64) (*TimeEntry, error) {
	var entry TimeEntry
	err := db.QueryRow(`
		SELECT id, client_id, start_time, end_time, comment
		FROM time_entries
		WHERE client_id = ? AND end_time IS NULL
		ORDER BY start_time DESC
		LIMIT 1
	`, clientID).Scan(&entry.ID, &entry.ClientID, &entry.StartTime, &entry.EndTime, &entry.Comment)

	if err == sql.ErrNoRows {
		return nil, nil // No running entry
	}
	if err != nil {
		return nil, fmt.Errorf("failed to query running entry: %w", err)
	}

	return &entry, nil
}

// GetLastCompletedEntry finds the most recently completed time entry for a client.
// Returns nil if no completed entries exist.
// Excludes invoiced entries to prevent modification of billed hours.
func GetLastCompletedEntry(db *sql.DB, clientID int64) (*TimeEntry, error) {
	var entry TimeEntry
	err := db.QueryRow(`
		SELECT id, client_id, start_time, end_time, comment
		FROM time_entries
		WHERE client_id = ? AND end_time IS NOT NULL AND invoice_id IS NULL
		ORDER BY end_time DESC
		LIMIT 1
	`, clientID).Scan(&entry.ID, &entry.ClientID, &entry.StartTime, &entry.EndTime, &entry.Comment)

	if err == sql.ErrNoRows {
		return nil, nil // No completed entries
	}
	if err != nil {
		return nil, fmt.Errorf("failed to query last completed entry: %w", err)
	}

	return &entry, nil
}

// StopEntry sets the end_time of an entry to the current time (snapped to next 15min).
func StopEntry(db *sql.DB, entryID int64) error {
	// Snap end time to next 15-minute mark (e.g., 14:37 → 14:45)
	snappedEnd := SnapToNext15Min(time.Now())

	_, err := db.Exec(`
		UPDATE time_entries
		SET end_time = ?
		WHERE id = ?
	`, snappedEnd.Unix(), entryID)

	if err != nil {
		return fmt.Errorf("failed to stop entry: %w", err)
	}

	return nil
}

// RestartEntry sets the end_time of an entry back to NULL (making it in-progress).
// Returns an error if the entry has been invoiced (to preserve billing integrity).
func RestartEntry(db *sql.DB, entryID int64) error {
	// Check if entry is invoiced
	var invoiceID sql.NullInt64
	err := db.QueryRow(`
		SELECT invoice_id
		FROM time_entries
		WHERE id = ?
	`, entryID).Scan(&invoiceID)

	if err != nil {
		return fmt.Errorf("failed to check entry status: %w", err)
	}

	if invoiceID.Valid {
		return fmt.Errorf("cannot restart invoiced entry (preserves billing integrity)")
	}

	_, err = db.Exec(`
		UPDATE time_entries
		SET end_time = NULL
		WHERE id = ?
	`, entryID)

	if err != nil {
		return fmt.Errorf("failed to restart entry: %w", err)
	}

	return nil
}

// StartNewEntry creates a new time entry with start_time=now (snapped to previous 15min) and end_time=NULL.
func StartNewEntry(db *sql.DB, clientID int64) error {
	// Snap start time to previous 15-minute mark (e.g., 14:37 → 14:30)
	snappedStart := SnapToPrevious15Min(time.Now())

	_, err := db.Exec(`
		INSERT INTO time_entries (client_id, start_time, end_time)
		VALUES (?, ?, NULL)
	`, clientID, snappedStart.Unix())

	if err != nil {
		return fmt.Errorf("failed to start new entry: %w", err)
	}

	return nil
}

// UpdateEntryStartTime adjusts the start_time of an entry by adding/subtracting minutes.
// Returns an error if the entry has been invoiced (to preserve billing integrity).
func UpdateEntryStartTime(db *sql.DB, entryID int64, minutesDelta int) error {
	// Check if entry is invoiced
	var invoiceID sql.NullInt64
	var startTime int64
	var endTime sql.NullInt64
	err := db.QueryRow(`
		SELECT invoice_id, start_time, end_time
		FROM time_entries
		WHERE id = ?
	`, entryID).Scan(&invoiceID, &startTime, &endTime)

	if err != nil {
		return fmt.Errorf("failed to check entry status: %w", err)
	}

	if invoiceID.Valid {
		return fmt.Errorf("cannot adjust invoiced entry (preserves billing integrity)")
	}

	// Calculate new start time
	newStartTime := startTime + int64(minutesDelta*60)

	// Validate: new start time must be before end time (if entry has end time)
	if endTime.Valid && newStartTime >= endTime.Int64 {
		return fmt.Errorf("start time must be before end time")
	}

	// Update the start time
	_, err = db.Exec(`
		UPDATE time_entries
		SET start_time = ?
		WHERE id = ?
	`, newStartTime, entryID)

	if err != nil {
		return fmt.Errorf("failed to update start time: %w", err)
	}

	return nil
}

// UpdateEntryEndTime adjusts the end_time of an entry by adding/subtracting minutes.
// Returns an error if:
//   - The entry has been invoiced (to preserve billing integrity)
//   - The entry is still running (end_time is NULL)
func UpdateEntryEndTime(db *sql.DB, entryID int64, minutesDelta int) error {
	// Check if entry is invoiced and get current times
	var invoiceID sql.NullInt64
	var startTime int64
	var endTime sql.NullInt64
	err := db.QueryRow(`
		SELECT invoice_id, start_time, end_time
		FROM time_entries
		WHERE id = ?
	`, entryID).Scan(&invoiceID, &startTime, &endTime)

	if err != nil {
		return fmt.Errorf("failed to check entry status: %w", err)
	}

	if invoiceID.Valid {
		return fmt.Errorf("cannot adjust invoiced entry (preserves billing integrity)")
	}

	if !endTime.Valid {
		return fmt.Errorf("cannot adjust end time of running entry (stop it first)")
	}

	// Calculate new end time
	newEndTime := endTime.Int64 + int64(minutesDelta*60)

	// Validate: new end time must be after start time
	if newEndTime <= startTime {
		return fmt.Errorf("end time must be after start time")
	}

	// Update the end time
	_, err = db.Exec(`
		UPDATE time_entries
		SET end_time = ?
		WHERE id = ?
	`, newEndTime, entryID)

	if err != nil {
		return fmt.Errorf("failed to update end time: %w", err)
	}

	return nil
}

// CreateClient creates a new client with the given name, shortcode, and default target hours.
func CreateClient(db *sql.DB, name, shortcode string) error {
	if name == "" {
		return fmt.Errorf("client name cannot be empty")
	}
	if shortcode == "" {
		return fmt.Errorf("client shortcode cannot be empty")
	}

	_, err := db.Exec(`
		INSERT INTO clients (name, shortcode, target_hours)
		VALUES (?, ?, 40.0)
	`, name, shortcode)

	if err != nil {
		return fmt.Errorf("failed to create client: %w", err)
	}

	return nil
}

// UpdateClientShortcode updates the shortcode for a client.
func UpdateClientShortcode(db *sql.DB, clientID int64, shortcode string) error {
	if shortcode == "" {
		return fmt.Errorf("shortcode cannot be empty")
	}

	_, err := db.Exec(`
		UPDATE clients
		SET shortcode = ?
		WHERE id = ?
	`, shortcode, clientID)

	if err != nil {
		return fmt.Errorf("failed to update client shortcode: %w", err)
	}

	return nil
}

// LoadArchivedClients loads all archived clients sorted by archived_at (most recent first).
func LoadArchivedClients(db *sql.DB) ([]Client, error) {
	// Query all archived clients, sorted by archived_at descending (most recent first)
	rows, err := db.Query(`
		SELECT id, name, shortcode, target_hours, archived, archived_at
		FROM clients
		WHERE archived = 1
		ORDER BY archived_at DESC, name
	`)
	if err != nil {
		return nil, fmt.Errorf("failed to query archived clients: %w", err)
	}
	defer rows.Close()

	var clients []Client
	for rows.Next() {
		var client Client
		var archivedInt int
		if err := rows.Scan(&client.ID, &client.Name, &client.Shortcode, &client.TargetHours, &archivedInt, &client.ArchivedAt); err != nil {
			return nil, fmt.Errorf("failed to scan archived client: %w", err)
		}
		client.Archived = (archivedInt != 0)

		// Load display items (entries + milestones) for this client
		displayItems, err := LoadClientDisplayItems(db, client.ID)
		if err != nil {
			return nil, fmt.Errorf("failed to load display items for archived client %s: %w", client.Name, err)
		}
		client.DisplayItems = displayItems

		clients = append(clients, client)
	}

	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("error iterating archived clients: %w", err)
	}

	return clients, nil
}

// ArchiveClient toggles the archived status of a client and updates the timestamp.
func ArchiveClient(db *sql.DB, clientID int64) error {
	_, err := db.Exec(`
		UPDATE clients
		SET archived = NOT archived,
		    archived_at = ?
		WHERE id = ?
	`, time.Now().Unix(), clientID)

	if err != nil {
		return fmt.Errorf("failed to toggle archive status: %w", err)
	}

	return nil
}

// UpdateEntryComment updates the comment field of a time entry.
// Returns an error if the entry has been invoiced (to preserve billing integrity).
func UpdateEntryComment(db *sql.DB, entryID int64, comment string) error {
	// Check if entry is invoiced
	var invoiceID sql.NullInt64
	err := db.QueryRow(`
		SELECT invoice_id
		FROM time_entries
		WHERE id = ?
	`, entryID).Scan(&invoiceID)

	if err != nil {
		return fmt.Errorf("failed to check entry status: %w", err)
	}

	if invoiceID.Valid {
		return fmt.Errorf("cannot edit invoiced entry (preserves billing integrity)")
	}

	_, err = db.Exec(`
		UPDATE time_entries
		SET comment = ?
		WHERE id = ?
	`, comment, entryID)

	if err != nil {
		return fmt.Errorf("failed to update entry comment: %w", err)
	}

	return nil
}

// DeleteEntry deletes a time entry from the database.
// Returns an error if the entry has been invoiced (to preserve billing integrity).
func DeleteEntry(db *sql.DB, entryID int64) error {
	// Check if entry is invoiced
	var invoiceID sql.NullInt64
	err := db.QueryRow(`
		SELECT invoice_id
		FROM time_entries
		WHERE id = ?
	`, entryID).Scan(&invoiceID)

	if err != nil {
		return fmt.Errorf("failed to check entry status: %w", err)
	}

	if invoiceID.Valid {
		return fmt.Errorf("cannot delete invoiced entry (preserves billing integrity)")
	}

	_, err = db.Exec(`
		DELETE FROM time_entries
		WHERE id = ?
	`, entryID)

	if err != nil {
		return fmt.Errorf("failed to delete entry: %w", err)
	}

	return nil
}

// normalizeClientName normalizes a client name for comparison by:
// - Decomposing Unicode characters (NFD)
// - Removing combining marks (accents, diacritics)
// - Converting to lowercase
// - Keeping only letters and digits
// - Removing all symbols and special characters
func normalizeClientName(name string) string {
	// Create transformer that:
	// 1. Decomposes Unicode (NFD) - separates base chars from accents
	// 2. Removes non-spacing marks (accents, diacritics)
	// 3. Composes back (NFC) for consistency
	t := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)

	// Apply transformation
	normalized, _, err := transform.String(t, name)
	if err != nil {
		// If transformation fails, fall back to original
		normalized = name
	}

	// Convert to lowercase and keep only alphanumeric
	var result strings.Builder
	for _, ch := range strings.ToLower(normalized) {
		if (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') {
			result.WriteRune(ch)
		}
	}

	return result.String()
}

// GetClientByName looks up a client by name. Returns nil if not found.
func GetClientByName(db *sql.DB, name string) (*Client, error) {
	var client Client
	var archivedInt int
	err := db.QueryRow(`
		SELECT id, name, shortcode, target_hours, archived, archived_at
		FROM clients
		WHERE name = ?
	`, name).Scan(&client.ID, &client.Name, &client.Shortcode, &client.TargetHours, &archivedInt, &client.ArchivedAt)

	if err == sql.ErrNoRows {
		return nil, nil // Client not found
	}
	if err != nil {
		return nil, fmt.Errorf("failed to query client: %w", err)
	}

	client.Archived = (archivedInt != 0)
	return &client, nil
}

// GetClientByNormalizedName looks up a client by normalized name.
// Returns the client and whether an exact match was found.
func GetClientByNormalizedName(db *sql.DB, name string) (*Client, bool, error) {
	normalized := normalizeClientName(name)

	// Get all clients and check for normalized match
	rows, err := db.Query(`
		SELECT id, name, shortcode, target_hours, archived, archived_at
		FROM clients
	`)
	if err != nil {
		return nil, false, fmt.Errorf("failed to query clients: %w", err)
	}
	defer rows.Close()

	for rows.Next() {
		var client Client
		var archivedInt int
		if err := rows.Scan(&client.ID, &client.Name, &client.Shortcode, &client.TargetHours, &archivedInt, &client.ArchivedAt); err != nil {
			return nil, false, fmt.Errorf("failed to scan client: %w", err)
		}
		client.Archived = (archivedInt != 0)

		if normalizeClientName(client.Name) == normalized {
			exactMatch := client.Name == name
			return &client, exactMatch, nil
		}
	}

	if err := rows.Err(); err != nil {
		return nil, false, fmt.Errorf("error iterating clients: %w", err)
	}

	return nil, false, nil // Client not found
}

// HasOpenEntry checks if a client has any open (in-progress) time entries.
func HasOpenEntry(db *sql.DB, clientID int64) (bool, error) {
	var count int
	err := db.QueryRow(`
		SELECT COUNT(*)
		FROM time_entries
		WHERE client_id = ? AND end_time IS NULL
	`, clientID).Scan(&count)

	if err != nil {
		return false, fmt.Errorf("failed to check for open entries: %w", err)
	}

	return count > 0, nil
}

// CheckTimeOverlap checks if a time range [startTime, endTime] overlaps with any existing
// time entries for a client. If endTime is 0, it represents an open entry (end_time IS NULL).
// Returns true if there's an overlap, false otherwise.
func CheckTimeOverlap(db *sql.DB, clientID int64, startTime int64, endTime int64) (bool, error) {
	var query string
	var args []any

	if endTime == 0 {
		// Checking for open entry - it overlaps with any existing entry that:
		// 1. Is open (end_time IS NULL), OR
		// 2. Has an end_time >= startTime (the new open entry would extend into it)
		query = `
			SELECT COUNT(*)
			FROM time_entries
			WHERE client_id = ? AND (
				end_time IS NULL OR
				end_time > ?
			)
		`
		args = []any{clientID, startTime}
	} else {
		// Checking for closed entry - overlaps when: start_time < endTime AND (end_time IS NULL OR end_time > startTime)
		query = `
			SELECT COUNT(*)
			FROM time_entries
			WHERE client_id = ? AND start_time < ? AND (end_time IS NULL OR end_time > ?)
		`
		args = []any{clientID, endTime, startTime}
	}

	var count int
	err := db.QueryRow(query, args...).Scan(&count)
	if err != nil {
		return false, fmt.Errorf("failed to check time overlap: %w", err)
	}

	return count > 0, nil
}

// CreateMilestone creates a new milestone for a client at the given timestamp.
func CreateMilestone(db *sql.DB, clientID int64, name string, timestamp int64) error {
	if name == "" {
		return fmt.Errorf("milestone name cannot be empty")
	}

	_, err := db.Exec(`
		INSERT INTO milestones (client_id, name, timestamp)
		VALUES (?, ?, ?)
	`, clientID, name, timestamp)

	if err != nil {
		return fmt.Errorf("failed to create milestone: %w", err)
	}

	return nil
}

// UpdateMilestone updates the name of an existing milestone.
func UpdateMilestone(db *sql.DB, milestoneID int64, name string) error {
	if name == "" {
		return fmt.Errorf("milestone name cannot be empty")
	}

	_, err := db.Exec(`
		UPDATE milestones
		SET name = ?
		WHERE id = ?
	`, name, milestoneID)

	if err != nil {
		return fmt.Errorf("failed to update milestone: %w", err)
	}

	return nil
}

// UpdateMilestoneTimestamp updates the timestamp of a milestone (used for movement).
func UpdateMilestoneTimestamp(db *sql.DB, milestoneID int64, timestamp int64) error {
	_, err := db.Exec(`
		UPDATE milestones
		SET timestamp = ?
		WHERE id = ?
	`, timestamp, milestoneID)

	if err != nil {
		return fmt.Errorf("failed to update milestone timestamp: %w", err)
	}

	return nil
}

// DeleteMilestone deletes a milestone from the database.
func DeleteMilestone(db *sql.DB, milestoneID int64) error {
	_, err := db.Exec(`
		DELETE FROM milestones
		WHERE id = ?
	`, milestoneID)

	if err != nil {
		return fmt.Errorf("failed to delete milestone: %w", err)
	}

	return nil
}

// LoadMilestones loads all milestones for a specific client.
func LoadMilestones(db *sql.DB, clientID int64) ([]Milestone, error) {
	rows, err := db.Query(`
		SELECT id, client_id, name, timestamp
		FROM milestones
		WHERE client_id = ?
		ORDER BY timestamp
	`, clientID)
	if err != nil {
		return nil, fmt.Errorf("failed to query milestones: %w", err)
	}
	defer rows.Close()

	var milestones []Milestone
	for rows.Next() {
		var milestone Milestone
		if err := rows.Scan(&milestone.ID, &milestone.ClientID, &milestone.Name, &milestone.Timestamp); err != nil {
			return nil, fmt.Errorf("failed to scan milestone: %w", err)
		}
		milestones = append(milestones, milestone)
	}

	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("error iterating milestones: %w", err)
	}

	return milestones, nil
}

// LoadClientDisplayItems loads time entries and milestones for a client,
// merges them into a unified sorted list, and calculates cumulative hours.
func LoadClientDisplayItems(db *sql.DB, clientID int64) ([]DisplayItem, error) {
	// Load time entries
	entries, err := loadTimeEntries(db, clientID)
	if err != nil {
		return nil, fmt.Errorf("failed to load entries: %w", err)
	}

	// Load milestones
	milestones, err := LoadMilestones(db, clientID)
	if err != nil {
		return nil, fmt.Errorf("failed to load milestones: %w", err)
	}

	// Create display items list
	var items []DisplayItem

	// Add entries
	for i := range entries {
		items = append(items, DisplayItem{
			ItemType:      "entry",
			Entry:         &entries[i],
			Milestone:     nil,
			SortTimestamp: entries[i].StartTime,
		})
	}

	// Add milestones (subtract 0.5 for sorting so milestones appear before entries at same timestamp)
	for i := range milestones {
		items = append(items, DisplayItem{
			ItemType:      "milestone",
			Entry:         nil,
			Milestone:     &milestones[i],
			SortTimestamp: milestones[i].Timestamp,
		})
	}

	// Sort by timestamp (milestones will appear before entries at same timestamp due to stable sort)
	// We need custom sort to ensure milestones come before entries at equal timestamps
	for i := 0; i < len(items); i++ {
		for j := i + 1; j < len(items); j++ {
			// Sort by timestamp first
			if items[i].SortTimestamp > items[j].SortTimestamp {
				items[i], items[j] = items[j], items[i]
			} else if items[i].SortTimestamp == items[j].SortTimestamp {
				// If equal, milestones come before entries
				if items[i].ItemType == "entry" && items[j].ItemType == "milestone" {
					items[i], items[j] = items[j], items[i]
				}
			}
		}
	}

	// Calculate hours between milestones and assign display indices
	// For each milestone, we calculate the hours from that milestone until the next milestone
	for i := range items {
		items[i].DisplayIndex = i + 1

		if items[i].ItemType == "milestone" {
			// Calculate hours from this milestone until the next milestone (or end of list)
			hours := 0.0
			for j := i + 1; j < len(items); j++ {
				if items[j].ItemType == "milestone" {
					// Found next milestone, stop counting
					break
				}
				// Count completed entries
				if items[j].ItemType == "entry" && items[j].Entry.EndTime.Valid {
					duration := float64(items[j].Entry.EndTime.Int64-items[j].Entry.StartTime) / 3600.0
					hours += duration
				}
			}
			items[i].CumulativeHours = hours
		}
	}

	return items, nil
}

// SaveUIState saves a UI state key-value pair to the database.
func SaveUIState(db *sql.DB, key, value string) error {
	_, err := db.Exec(`
		INSERT INTO ui_state (key, value)
		VALUES (?, ?)
		ON CONFLICT(key) DO UPDATE SET value = excluded.value
	`, key, value)

	if err != nil {
		return fmt.Errorf("failed to save UI state: %w", err)
	}

	return nil
}

// LoadUIState loads a UI state value by key from the database.
// Returns empty string if key doesn't exist.
func LoadUIState(db *sql.DB, key string) (string, error) {
	var value string
	err := db.QueryRow(`
		SELECT value
		FROM ui_state
		WHERE key = ?
	`, key).Scan(&value)

	if err == sql.ErrNoRows {
		return "", nil // Key doesn't exist
	}
	if err != nil {
		return "", fmt.Errorf("failed to load UI state: %w", err)
	}

	return value, nil
}