package com.example.todolist.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.example.todolist.entity.AttachedFile;

@Repository
public interface AttachedFileRepository extends JpaRepository<AttachedFile, Integer> {

    // SELECT * FROM attached_file WHERE todo_id = todoId ORER BY id に相当
    List<AttachedFile> findByTodoIdOrderById(Integer todoId);

    @Query(value = """
            SELECT CASE WHEN COUNT(*) > 0 THEN TRUE ELSE FALSE END
              FROM attached_file af
              JOIN todo t
                ON t.id = af.todo_id
             WHERE af.id = :afId
               AND t.owner_id = :ownerId
            """, nativeQuery = true)
    boolean existsByIdAndOwnerIdNative(
            @Param("afId") int afId,
            @Param("ownerId") int ownerId);
}
