summaryrefslogblamecommitdiff
path: root/makima/src/server/handlers/users.rs
blob: 0b2ccddb44e06288c84dc108d9ce14337163d33c (plain) (tree)
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











































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                                                                   
//! HTTP handlers for user account management.
//!
//! These endpoints allow users to manage their account settings:
//! - Change password
//! - Change email
//! - Delete account

use axum::{
    extract::State,
    http::{HeaderMap, StatusCode},
    response::IntoResponse,
    Json,
};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;

use crate::server::auth::UserOnly;
use crate::server::messages::ApiError;
use crate::server::state::SharedState;

// =============================================================================
// Request/Response Types
// =============================================================================

/// Request to change password.
#[derive(Debug, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ChangePasswordRequest {
    /// The user's current password for verification
    pub current_password: String,
    /// The new password to set
    pub new_password: String,
}

/// Response after changing password.
#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ChangePasswordResponse {
    pub success: bool,
    pub message: String,
}

/// Request to change email.
#[derive(Debug, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ChangeEmailRequest {
    /// The user's password for verification
    pub password: String,
    /// The new email address to set
    pub new_email: String,
}

/// Response after changing email.
#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ChangeEmailResponse {
    pub success: bool,
    pub message: String,
    /// Whether a verification email was sent to the new address
    pub verification_sent: bool,
}

/// Request to delete account.
#[derive(Debug, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct DeleteAccountRequest {
    /// The user's password for verification
    pub password: String,
    /// Confirmation text - must match the user's email
    pub confirmation: String,
}

/// Response after deleting account.
#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct DeleteAccountResponse {
    pub success: bool,
    pub message: String,
}

// =============================================================================
// Password Validation
// =============================================================================

/// Password strength validation result.
#[derive(Debug)]
pub struct PasswordValidation {
    pub is_valid: bool,
    pub errors: Vec<String>,
}

/// Validate password strength.
/// Requirements:
/// - At least 6 characters (matches login form)
fn validate_password_strength(password: &str) -> PasswordValidation {
    let mut errors = Vec::new();

    if password.len() < 6 {
        errors.push("Password must be at least 6 characters long".to_string());
    }

    PasswordValidation {
        is_valid: errors.is_empty(),
        errors,
    }
}

/// Validate email format.
fn validate_email(email: &str) -> bool {
    // Basic email validation - must contain @ and at least one . after @
    let parts: Vec<&str> = email.split('@').collect();
    if parts.len() != 2 {
        return false;
    }
    let local = parts[0];
    let domain = parts[1];
    // Local part must not be empty
    if local.is_empty() {
        return false;
    }
    // Domain must have at least one dot and not start/end with dot
    domain.contains('.') && !domain.starts_with('.') && !domain.ends_with('.')
}

// =============================================================================
// Supabase Admin Client
// =============================================================================

/// Supabase Admin API client for user management operations.
/// Uses the service role key for admin-level operations.
pub struct SupabaseAdminClient {
    base_url: String,
    secret_api_key: String,
    client: reqwest::Client,
}

impl SupabaseAdminClient {
    /// Create a new Supabase admin client from environment variables.
    pub fn from_env() -> Option<Self> {
        let base_url = std::env::var("SUPABASE_URL").ok()?;
        let secret_api_key = std::env::var("SUPABASE_SECRET_API_KEY").ok()?;

        Some(Self {
            base_url,
            secret_api_key,
            client: reqwest::Client::new(),
        })
    }

    /// Verify a user's password by attempting to sign in.
    pub async fn verify_password(&self, email: &str, password: &str) -> Result<bool, String> {
        let url = format!("{}/auth/v1/token?grant_type=password", self.base_url);

        let response = self
            .client
            .post(&url)
            .header("apikey", &self.secret_api_key)
            .header("Content-Type", "application/json")
            .json(&serde_json::json!({
                "email": email,
                "password": password
            }))
            .send()
            .await
            .map_err(|e| format!("Failed to verify password: {}", e))?;

        Ok(response.status().is_success())
    }

    /// Update a user's password.
    pub async fn update_password(
        &self,
        user_id: &str,
        new_password: &str,
    ) -> Result<(), String> {
        let url = format!("{}/auth/v1/admin/users/{}", self.base_url, user_id);

        let response = self
            .client
            .put(&url)
            .header("apikey", &self.secret_api_key)
            .header("Authorization", format!("Bearer {}", self.secret_api_key))
            .header("Content-Type", "application/json")
            .json(&serde_json::json!({
                "password": new_password
            }))
            .send()
            .await
            .map_err(|e| format!("Failed to update password: {}", e))?;

        if response.status().is_success() {
            Ok(())
        } else {
            let error_text = response.text().await.unwrap_or_default();
            Err(format!("Failed to update password: {}", error_text))
        }
    }

    /// Update a user's email.
    pub async fn update_email(
        &self,
        user_id: &str,
        new_email: &str,
    ) -> Result<(), String> {
        let url = format!("{}/auth/v1/admin/users/{}", self.base_url, user_id);

        let response = self
            .client
            .put(&url)
            .header("apikey", &self.secret_api_key)
            .header("Authorization", format!("Bearer {}", self.secret_api_key))
            .header("Content-Type", "application/json")
            .json(&serde_json::json!({
                "email": new_email,
                "email_confirm": true
            }))
            .send()
            .await
            .map_err(|e| format!("Failed to update email: {}", e))?;

        if response.status().is_success() {
            Ok(())
        } else {
            let error_text = response.text().await.unwrap_or_default();
            Err(format!("Failed to update email: {}", error_text))
        }
    }

    /// Delete a user from Supabase Auth.
    pub async fn delete_user(&self, user_id: &str) -> Result<(), String> {
        let url = format!("{}/auth/v1/admin/users/{}", self.base_url, user_id);

        let response = self
            .client
            .delete(&url)
            .header("apikey", &self.secret_api_key)
            .header("Authorization", format!("Bearer {}", self.secret_api_key))
            .send()
            .await
            .map_err(|e| format!("Failed to delete user: {}", e))?;

        if response.status().is_success() {
            Ok(())
        } else {
            let error_text = response.text().await.unwrap_or_default();
            Err(format!("Failed to delete user: {}", error_text))
        }
    }

    /// Get user info including email.
    pub async fn get_user(&self, user_id: &str) -> Result<Option<String>, String> {
        let url = format!("{}/auth/v1/admin/users/{}", self.base_url, user_id);

        let response = self
            .client
            .get(&url)
            .header("apikey", &self.secret_api_key)
            .header("Authorization", format!("Bearer {}", self.secret_api_key))
            .send()
            .await
            .map_err(|e| format!("Failed to get user: {}", e))?;

        if response.status().is_success() {
            let json: serde_json::Value = response
                .json()
                .await
                .map_err(|e| format!("Failed to parse user data: {}", e))?;
            Ok(json.get("email").and_then(|e| e.as_str()).map(String::from))
        } else if response.status() == reqwest::StatusCode::NOT_FOUND {
            Ok(None)
        } else {
            let error_text = response.text().await.unwrap_or_default();
            Err(format!("Failed to get user: {}", error_text))
        }
    }
}

// =============================================================================
// Supabase User Client (uses user's JWT, no admin required)
// =============================================================================

/// Supabase User API client for self-service operations.
/// Uses the user's JWT token - no admin/service role key required.
pub struct SupabaseUserClient {
    base_url: String,
    anon_key: String,
    jwt_token: String,
    client: reqwest::Client,
}

impl SupabaseUserClient {
    /// Create a new Supabase user client from environment and JWT token.
    pub fn new(jwt_token: String) -> Option<Self> {
        let base_url = std::env::var("SUPABASE_URL").ok()?;
        let anon_key = std::env::var("SUPABASE_ANON_KEY").ok()?;

        Some(Self {
            base_url,
            anon_key,
            jwt_token,
            client: reqwest::Client::new(),
        })
    }

    /// Update the user's password using their own JWT.
    pub async fn update_password(&self, new_password: &str) -> Result<(), String> {
        let url = format!("{}/auth/v1/user", self.base_url);

        let response = self
            .client
            .put(&url)
            .header("apikey", &self.anon_key)
            .header("Authorization", format!("Bearer {}", self.jwt_token))
            .header("Content-Type", "application/json")
            .json(&serde_json::json!({
                "password": new_password
            }))
            .send()
            .await
            .map_err(|e| format!("Failed to update password: {}", e))?;

        if response.status().is_success() {
            Ok(())
        } else {
            let error_text = response.text().await.unwrap_or_default();
            Err(format!("Failed to update password: {}", error_text))
        }
    }

    /// Update the user's email using their own JWT.
    pub async fn update_email(&self, new_email: &str) -> Result<(), String> {
        let url = format!("{}/auth/v1/user", self.base_url);

        let response = self
            .client
            .put(&url)
            .header("apikey", &self.anon_key)
            .header("Authorization", format!("Bearer {}", self.jwt_token))
            .header("Content-Type", "application/json")
            .json(&serde_json::json!({
                "email": new_email
            }))
            .send()
            .await
            .map_err(|e| format!("Failed to update email: {}", e))?;

        if response.status().is_success() {
            Ok(())
        } else {
            let error_text = response.text().await.unwrap_or_default();
            Err(format!("Failed to update email: {}", error_text))
        }
    }

    /// Verify current password by attempting to sign in.
    pub async fn verify_password(&self, email: &str, password: &str) -> Result<bool, String> {
        let url = format!("{}/auth/v1/token?grant_type=password", self.base_url);

        let response = self
            .client
            .post(&url)
            .header("apikey", &self.anon_key)
            .header("Content-Type", "application/json")
            .json(&serde_json::json!({
                "email": email,
                "password": password
            }))
            .send()
            .await
            .map_err(|e| format!("Failed to verify password: {}", e))?;

        Ok(response.status().is_success())
    }
}

// =============================================================================
// Handlers
// =============================================================================

/// Change the authenticated user's password.
///
/// Requires verification of the current password before allowing the change.
/// The new password must meet strength requirements.
#[utoipa::path(
    put,
    path = "/api/v1/users/me/password",
    request_body = ChangePasswordRequest,
    responses(
        (status = 200, description = "Password changed successfully", body = ChangePasswordResponse),
        (status = 400, description = "Invalid request (weak password, wrong current password)", body = ApiError),
        (status = 401, description = "Not authenticated", body = ApiError),
        (status = 403, description = "Forbidden (tool keys not allowed)", body = ApiError),
        (status = 503, description = "Supabase not configured", body = ApiError),
        (status = 500, description = "Internal server error", body = ApiError),
    ),
    security(
        ("bearer_auth" = [])
    ),
    tag = "Users"
)]
pub async fn change_password_handler(
    State(_state): State<SharedState>,
    headers: HeaderMap,
    UserOnly(user): UserOnly,
    Json(req): Json<ChangePasswordRequest>,
) -> impl IntoResponse {
    // Validate new password strength
    let validation = validate_password_strength(&req.new_password);
    if !validation.is_valid {
        return (
            StatusCode::BAD_REQUEST,
            Json(ApiError::new(
                "WEAK_PASSWORD",
                &validation.errors.join("; "),
            )),
        )
            .into_response();
    }

    // Get user's email (required for password verification)
    let email = match &user.email {
        Some(email) => email.clone(),
        None => {
            return (
                StatusCode::BAD_REQUEST,
                Json(ApiError::new("EMAIL_REQUIRED", "User email not available")),
            )
                .into_response();
        }
    };

    // Extract JWT from Authorization header for user-level API calls
    let jwt_token = headers
        .get("Authorization")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| s.strip_prefix("Bearer "))
        .map(|s| s.to_string());

    // Try user client first (uses JWT, no admin required), fall back to admin client
    if let Some(token) = jwt_token {
        if let Some(user_client) = SupabaseUserClient::new(token) {
            // Verify current password
            match user_client.verify_password(&email, &req.current_password).await {
                Ok(true) => {}
                Ok(false) => {
                    return (
                        StatusCode::BAD_REQUEST,
                        Json(ApiError::new("INVALID_PASSWORD", "Current password is incorrect")),
                    )
                        .into_response();
                }
                Err(e) => {
                    tracing::error!("Failed to verify password: {}", e);
                    return (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        Json(ApiError::new("INTERNAL_ERROR", "Failed to verify password")),
                    )
                        .into_response();
                }
            }

            // Update password using user's JWT
            return match user_client.update_password(&req.new_password).await {
                Ok(()) => {
                    tracing::info!("Password changed for user {}", user.user_id);
                    Json(ChangePasswordResponse {
                        success: true,
                        message: "Password changed successfully".to_string(),
                    })
                    .into_response()
                }
                Err(e) => {
                    tracing::error!("Failed to update password: {}", e);
                    (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        Json(ApiError::new("INTERNAL_ERROR", "Failed to update password")),
                    )
                        .into_response()
                }
            };
        }
    }

    // Fall back to admin client if user client not available
    let admin_client = match SupabaseAdminClient::from_env() {
        Some(client) => client,
        None => {
            return (
                StatusCode::SERVICE_UNAVAILABLE,
                Json(ApiError::new(
                    "SUPABASE_NOT_CONFIGURED",
                    "Supabase not configured. Ensure SUPABASE_URL and SUPABASE_ANON_KEY are set.",
                )),
            )
                .into_response();
        }
    };

    // Verify current password
    match admin_client.verify_password(&email, &req.current_password).await {
        Ok(true) => {}
        Ok(false) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(ApiError::new("INVALID_PASSWORD", "Current password is incorrect")),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("Failed to verify password: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("INTERNAL_ERROR", "Failed to verify password")),
            )
                .into_response();
        }
    }

    // Update password in Supabase
    match admin_client
        .update_password(&user.user_id.to_string(), &req.new_password)
        .await
    {
        Ok(()) => {
            tracing::info!("Password changed for user {}", user.user_id);
            Json(ChangePasswordResponse {
                success: true,
                message: "Password changed successfully".to_string(),
            })
            .into_response()
        }
        Err(e) => {
            tracing::error!("Failed to update password: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("INTERNAL_ERROR", "Failed to update password")),
            )
                .into_response()
        }
    }
}

/// Change the authenticated user's email address.
///
/// Requires password verification before allowing the change.
/// The new email will be updated directly (Supabase handles verification if configured).
#[utoipa::path(
    put,
    path = "/api/v1/users/me/email",
    request_body = ChangeEmailRequest,
    responses(
        (status = 200, description = "Email changed successfully", body = ChangeEmailResponse),
        (status = 400, description = "Invalid request (invalid email, wrong password)", body = ApiError),
        (status = 401, description = "Not authenticated", body = ApiError),
        (status = 403, description = "Forbidden (tool keys not allowed)", body = ApiError),
        (status = 503, description = "Supabase not configured", body = ApiError),
        (status = 500, description = "Internal server error", body = ApiError),
    ),
    security(
        ("bearer_auth" = [])
    ),
    tag = "Users"
)]
pub async fn change_email_handler(
    State(state): State<SharedState>,
    headers: HeaderMap,
    UserOnly(user): UserOnly,
    Json(req): Json<ChangeEmailRequest>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Validate new email format
    if !validate_email(&req.new_email) {
        return (
            StatusCode::BAD_REQUEST,
            Json(ApiError::new("INVALID_EMAIL", "Invalid email format")),
        )
            .into_response();
    }

    // Get user's current email (required for password verification)
    let current_email = match &user.email {
        Some(email) => email.clone(),
        None => {
            return (
                StatusCode::BAD_REQUEST,
                Json(ApiError::new("EMAIL_REQUIRED", "User email not available")),
            )
                .into_response();
        }
    };

    // Extract JWT from Authorization header for user-level API calls
    let jwt_token = headers
        .get("Authorization")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| s.strip_prefix("Bearer "))
        .map(|s| s.to_string());

    // Try user client first (uses JWT, no admin required), fall back to admin client
    if let Some(token) = jwt_token {
        if let Some(user_client) = SupabaseUserClient::new(token) {
            // Verify password
            match user_client.verify_password(&current_email, &req.password).await {
                Ok(true) => {}
                Ok(false) => {
                    return (
                        StatusCode::BAD_REQUEST,
                        Json(ApiError::new("INVALID_PASSWORD", "Password is incorrect")),
                    )
                        .into_response();
                }
                Err(e) => {
                    tracing::error!("Failed to verify password: {}", e);
                    return (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        Json(ApiError::new("INTERNAL_ERROR", "Failed to verify password")),
                    )
                        .into_response();
                }
            }

            // Update email using user's JWT
            if let Err(e) = user_client.update_email(&req.new_email).await {
                tracing::error!("Failed to update email in Supabase: {}", e);
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(ApiError::new("INTERNAL_ERROR", "Failed to update email")),
                )
                    .into_response();
            }

            // Update email in our database
            if let Err(e) = sqlx::query("UPDATE users SET email = $1, updated_at = NOW() WHERE id = $2")
                .bind(&req.new_email)
                .bind(user.user_id)
                .execute(pool)
                .await
            {
                tracing::error!("Failed to update email in database: {}", e);
            }

            tracing::info!(
                "Email changed for user {} from {} to {}",
                user.user_id,
                current_email,
                req.new_email
            );

            return Json(ChangeEmailResponse {
                success: true,
                message: "Email changed successfully".to_string(),
                verification_sent: false,
            })
            .into_response();
        }
    }

    // Fall back to admin client if user client not available
    let admin_client = match SupabaseAdminClient::from_env() {
        Some(client) => client,
        None => {
            return (
                StatusCode::SERVICE_UNAVAILABLE,
                Json(ApiError::new(
                    "SUPABASE_NOT_CONFIGURED",
                    "Supabase not configured. Ensure SUPABASE_URL and SUPABASE_ANON_KEY are set.",
                )),
            )
                .into_response();
        }
    };

    // Verify password
    match admin_client.verify_password(&current_email, &req.password).await {
        Ok(true) => {}
        Ok(false) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(ApiError::new("INVALID_PASSWORD", "Password is incorrect")),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("Failed to verify password: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("INTERNAL_ERROR", "Failed to verify password")),
            )
                .into_response();
        }
    }

    // Update email in Supabase
    if let Err(e) = admin_client
        .update_email(&user.user_id.to_string(), &req.new_email)
        .await
    {
        tracing::error!("Failed to update email in Supabase: {}", e);
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ApiError::new("INTERNAL_ERROR", "Failed to update email")),
        )
            .into_response();
    }

    // Update email in our database
    if let Err(e) = sqlx::query("UPDATE users SET email = $1, updated_at = NOW() WHERE id = $2")
        .bind(&req.new_email)
        .bind(user.user_id)
        .execute(pool)
        .await
    {
        tracing::error!("Failed to update email in database: {}", e);
    }

    tracing::info!(
        "Email changed for user {} from {} to {}",
        user.user_id,
        current_email,
        req.new_email
    );

    Json(ChangeEmailResponse {
        success: true,
        message: "Email changed successfully".to_string(),
        verification_sent: false,
    })
    .into_response()
}

/// Delete the authenticated user's account.
///
/// This permanently deletes:
/// - The user's Supabase Auth account
/// - The user's record in our database
/// - All associated data (API keys, files, tasks, etc. via CASCADE)
///
/// Requires password verification and confirmation text matching the user's email.
#[utoipa::path(
    delete,
    path = "/api/v1/users/me",
    request_body = DeleteAccountRequest,
    responses(
        (status = 200, description = "Account deleted successfully", body = DeleteAccountResponse),
        (status = 400, description = "Invalid request (wrong password, wrong confirmation)", body = ApiError),
        (status = 401, description = "Not authenticated", body = ApiError),
        (status = 403, description = "Forbidden (tool keys not allowed)", body = ApiError),
        (status = 503, description = "Supabase not configured", body = ApiError),
        (status = 500, description = "Internal server error", body = ApiError),
    ),
    security(
        ("bearer_auth" = [])
    ),
    tag = "Users"
)]
pub async fn delete_account_handler(
    State(state): State<SharedState>,
    UserOnly(user): UserOnly,
    Json(req): Json<DeleteAccountRequest>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Get Supabase admin client - required for full account deletion
    let admin_client = match SupabaseAdminClient::from_env() {
        Some(client) => client,
        None => {
            return (
                StatusCode::SERVICE_UNAVAILABLE,
                Json(ApiError::new(
                    "SUPABASE_ADMIN_NOT_CONFIGURED",
                    "Account deletion requires SUPABASE_SECRET_API_KEY to be configured",
                )),
            )
                .into_response();
        }
    };

    // Verify confirmation is "DELETE MY ACCOUNT"
    const REQUIRED_CONFIRMATION: &str = "DELETE MY ACCOUNT";
    if req.confirmation != REQUIRED_CONFIRMATION {
        return (
            StatusCode::BAD_REQUEST,
            Json(ApiError::new(
                "INVALID_CONFIRMATION",
                format!("Confirmation text must be exactly: {}", REQUIRED_CONFIRMATION),
            )),
        )
            .into_response();
    }

    // Get user's email (required for password verification)
    let email = match &user.email {
        Some(e) => e.clone(),
        None => {
            return (
                StatusCode::BAD_REQUEST,
                Json(ApiError::new("EMAIL_REQUIRED", "User email not available")),
            )
                .into_response();
        }
    };

    // Verify password
    match admin_client.verify_password(&email, &req.password).await {
        Ok(true) => {}
        Ok(false) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(ApiError::new("INVALID_PASSWORD", "Password is incorrect")),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("Failed to verify password: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("INTERNAL_ERROR", "Failed to verify password")),
            )
                .into_response();
        }
    }

    // Delete from our database first (this will cascade to related records)
    // Get the owner_id before deleting
    let owner_id = user.owner_id;

    // Delete API keys for this user (explicit deletion for audit purposes)
    if let Err(e) = sqlx::query("UPDATE api_keys SET revoked_at = NOW() WHERE user_id = $1 AND revoked_at IS NULL")
        .bind(user.user_id)
        .execute(pool)
        .await
    {
        tracing::warn!("Failed to revoke API keys during account deletion: {}", e);
    }

    // Delete user record
    if let Err(e) = sqlx::query("DELETE FROM users WHERE id = $1")
        .bind(user.user_id)
        .execute(pool)
        .await
    {
        tracing::error!("Failed to delete user from database: {}", e);
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ApiError::new("INTERNAL_ERROR", "Failed to delete account")),
        )
            .into_response();
    }

    // Delete files owned by this user
    if let Err(e) = sqlx::query("DELETE FROM files WHERE owner_id = $1")
        .bind(owner_id)
        .execute(pool)
        .await
    {
        tracing::warn!("Failed to delete user files: {}", e);
    }

    // Delete tasks owned by this user
    if let Err(e) = sqlx::query("DELETE FROM tasks WHERE owner_id = $1")
        .bind(owner_id)
        .execute(pool)
        .await
    {
        tracing::warn!("Failed to delete user tasks: {}", e);
    }

    // Delete mesh chat conversations owned by this user
    if let Err(e) = sqlx::query("DELETE FROM mesh_chat_conversations WHERE owner_id = $1")
        .bind(owner_id)
        .execute(pool)
        .await
    {
        tracing::warn!("Failed to delete mesh chat conversations: {}", e);
    }

    // Delete daemons owned by this user
    if let Err(e) = sqlx::query("DELETE FROM daemons WHERE owner_id = $1")
        .bind(owner_id)
        .execute(pool)
        .await
    {
        tracing::warn!("Failed to delete user daemons: {}", e);
    }

    // Delete owner record
    if let Err(e) = sqlx::query("DELETE FROM owners WHERE id = $1")
        .bind(owner_id)
        .execute(pool)
        .await
    {
        tracing::warn!("Failed to delete owner record: {}", e);
    }

    // Delete from Supabase Auth
    if let Err(e) = admin_client.delete_user(&user.user_id.to_string()).await {
        tracing::error!("Failed to delete user from Supabase Auth: {}", e);
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ApiError::new(
                "SUPABASE_DELETE_FAILED",
                "Failed to delete user from authentication system",
            )),
        )
            .into_response();
    }

    tracing::info!("Account deleted for user {} ({})", user.user_id, email);

    Json(DeleteAccountResponse {
        success: true,
        message: "Account deleted successfully".to_string(),
    })
    .into_response()
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_password_validation_success() {
        // Minimum 6 characters
        let result = validate_password_strength("abcdef");
        assert!(result.is_valid);
        assert!(result.errors.is_empty());

        let result = validate_password_strength("Password123");
        assert!(result.is_valid);
        assert!(result.errors.is_empty());
    }

    #[test]
    fn test_password_validation_too_short() {
        let result = validate_password_strength("12345");
        assert!(!result.is_valid);
        assert!(result.errors.iter().any(|e| e.contains("6 characters")));
    }

    #[test]
    fn test_email_validation_valid() {
        assert!(validate_email("user@example.com"));
        assert!(validate_email("user.name@example.co.uk"));
        assert!(validate_email("user+tag@example.org"));
    }

    #[test]
    fn test_email_validation_invalid() {
        assert!(!validate_email("userexample.com"));
        assert!(!validate_email("user@"));
        assert!(!validate_email("@example.com"));
        assert!(!validate_email("user@.com"));
        assert!(!validate_email("user@example."));
    }
}