package com.alttd.altitudeweb.database.web_db.mail;

import org.apache.ibatis.annotations.*;

import java.time.Instant;
import java.util.UUID;

public interface EmailVerificationMapper {

    @Insert("""
            INSERT INTO user_emails (id, user_uuid, email, verification_code, verified, created_at, last_sent_at)
            VALUES (#{id}, #{userUuid}, #{email}, #{verificationCode}, #{verified}, #{createdAt}, #{lastSentAt})
            """)
    void insert(EmailVerification emailVerification);

    @Select("""
            SELECT id, user_uuid AS userUuid, email, verification_code AS verificationCode, verified,
                   created_at AS createdAt, verified_at AS verifiedAt, last_sent_at AS lastSentAt
            FROM user_emails
            WHERE user_uuid = #{userUuid} AND email = #{email}
            """)
    EmailVerification findByUserAndEmail(@Param("userUuid") UUID userUuid, @Param("email") String email);

    @Select("""
            SELECT id, user_uuid AS userUuid, email, verification_code AS verificationCode, verified,
                   created_at AS createdAt, verified_at AS verifiedAt, last_sent_at AS lastSentAt
            FROM user_emails
            WHERE user_uuid = #{userUuid} AND verification_code = #{code}
            ORDER BY created_at DESC LIMIT 1
            """)
    EmailVerification findByUserAndCode(@Param("userUuid") UUID userUuid, @Param("code") String code);

    @Select("""
            SELECT id, user_uuid AS userUuid, email, verification_code AS verificationCode, verified,
                   created_at AS createdAt, verified_at AS verifiedAt, last_sent_at AS lastSentAt
            FROM user_emails
            WHERE user_uuid = #{userUuid}
            ORDER BY created_at ASC
            """)
    java.util.List<EmailVerification> findAllByUser(@Param("userUuid") UUID userUuid);

    @Update("""
            UPDATE user_emails SET verified = 1, verified_at = #{verifiedAt}
            WHERE id = #{id}
            """)
    void markVerified(@Param("id") UUID id, @Param("verifiedAt") Instant verifiedAt);

    @Update("""
            UPDATE user_emails SET verification_code = #{code}, last_sent_at = #{lastSentAt}, verified = 0, verified_at = NULL
            WHERE id = #{id}
            """)
    void updateCodeAndLastSent(@Param("id") UUID id, @Param("code") String code, @Param("lastSentAt") Instant lastSentAt);

    @Delete("""
            DELETE FROM user_emails WHERE user_uuid = #{userUuid} AND email = #{email}
            """)
    void deleteByUserAndEmail(@Param("userUuid") UUID userUuid, @Param("email") String email);
}
