modules/backend/Write-Persistence-Dapper.ps1

param(
    [string]$ProjectName,
    [string]$OrmMode,
    [string]$DbProvider,
    [string]$OutputPath,
    [string[]]$Entities
)

if ($OrmMode -ne "Dapper") { return }

. (Join-Path (Split-Path $MyInvocation.MyCommand.Path) "..\core\Utils.ps1")

$base = Join-Path $OutputPath "src\$ProjectName.Persistence"
function Write-File($rel, $con) { Write-CoreFile (Join-Path $base $rel) $con }
function T($template, $e = "") { 
    $res = $template.Replace("{P}", $ProjectName)
    if ($e) { $res = $res.Replace("{E}", $e) }
    return $res
}

function Get-IdentitySql {
    param($table, $cols, $vals)
    switch ($DbProvider) {
        "Postgres" { "INSERT INTO $table ($cols) VALUES ($vals) RETURNING Id" }
        default    { "INSERT INTO $table ($cols) VALUES ($vals) OUTPUT INSERTED.Id" }
    }
}

function Get-PagedSql {
    param($table, $cols)
    switch ($DbProvider) {
        "Postgres" { "SELECT $cols FROM $table WHERE IsDeleted=@IsDeleted ORDER BY Id LIMIT @Size OFFSET @Offset" }
        default    { "SELECT $cols FROM $table WHERE IsDeleted=@IsDeleted ORDER BY Id OFFSET @Offset ROWS FETCH NEXT @Size ROWS ONLY" }
    }
}

foreach ($e in $Entities) {
    $pE = Get-Plural $e
    if ($e -eq "User") {
        $userSql = Get-IdentitySql "Users" "Username, PasswordHash, Email, IsActive, CreatedAt, UpdatedAt" "@Username, @PasswordHash, @Email, @IsActive, @CreatedAt, @UpdatedAt"
        Write-File "Repositories\UserRepository.cs" (T @"
using System.Data;
using Dapper;
using {P}.Domain.Entities;
using {P}.Domain.Interfaces;
 
namespace {P}.Persistence.Repositories;
 
public class UserRepository : IUserRepository
{
    private readonly IDbConnection _connection;
    public UserRepository(IDbConnection connection) => _connection = connection;
 
    public async Task<User?> GetByUsernameAsync(string u) =>
        await _connection.QueryFirstOrDefaultAsync<User>(
            "SELECT Id, Username, PasswordHash, Email, IsActive, Role, CreatedAt, UpdatedAt, IsDeleted FROM Users WHERE Username=@u",
            new { u });
 
    public async Task<int> AddAsync(User u) =>
        await _connection.ExecuteScalarAsync<int>("$userSql", u);
}
"@
)
    } else {
        $p = if ($e -eq "Product") { ", Price" } else { "" }
        $v = if ($e -eq "Product") { ", @Price" } else { "" }
        $u = if ($e -eq "Product") { ", Price=@Price" } else { "" }
        $sql = Get-IdentitySql $pE "Name, CreatedAt, UpdatedAt$p" "@Name, @CreatedAt, @UpdatedAt$v"
        
        $cols = "Id, Name$p, CreatedAt, UpdatedAt, IsDeleted"
        $pagedSql = Get-PagedSql $pE $cols

        Write-File "Repositories\$e`Repository.cs" (T @'
using System.Data;
using Dapper;
using {P}.Domain.Common;
using {P}.Domain.Entities;
using {P}.Domain.Interfaces;
 
namespace {P}.Persistence.Repositories;
 
public class {E}Repository : I{E}Repository
{
    private readonly IDbConnection _connection;
    public {E}Repository(IDbConnection connection) => _connection = connection;
 
    public async Task<{E}?> GetByIdAsync(int id) =>
        await _connection.QueryFirstOrDefaultAsync<{E}>(
            "SELECT {Cols} FROM {PE} WHERE Id=@id AND IsDeleted=@IsDeleted",
            new { id, IsDeleted = false });
 
    public async Task<IEnumerable<{E}>> GetAllAsync() =>
        await _connection.QueryAsync<{E}>(
            "SELECT {Cols} FROM {PE} WHERE IsDeleted=@IsDeleted",
            new { IsDeleted = false });
 
    public async Task<PagedResult<{E}>> GetPagedAsync(PagedQuery query)
    {
        var total = await _connection.ExecuteScalarAsync<int>(
            "SELECT COUNT(*) FROM {PE} WHERE IsDeleted=@IsDeleted",
            new { IsDeleted = false });
 
        var items = await _connection.QueryAsync<{E}>(
            BTICK{PagedSql}BTICK,
            new { Offset = query.Skip, query.Size, IsDeleted = false });
 
        return new PagedResult<{E}> { Items = items, TotalCount = total, Page = query.Page, Size = query.Size };
    }
 
    public async Task<int> AddAsync({E} e) =>
        await _connection.ExecuteScalarAsync<int>(BTICK $sqlBTICK, e);
 
    public async Task UpdateAsync({E} e) =>
        await _connection.ExecuteAsync(BTICK UPDATE {PE} SET Name=@Name, UpdatedAt=@UpdatedAt$sqlUpdate WHERE Id=@IdBTICK, e);
 
    public async Task DeleteAsync(int id) =>
        await _connection.ExecuteAsync(
            "UPDATE {PE} SET IsDeleted=@IsDeleted, UpdatedAt=@UpdatedAt WHERE Id=@id",
            new { id, IsDeleted = true, UpdatedAt = DateTime.UtcNow });
}
'@
 $e | % {
    $_.Replace("{PE}", $pE).Replace("{P}", $ProjectName).Replace("BTICK", "`"").Replace('$sqlUpdate', $u).Replace('$sql', $sql).Replace('{PagedSql}', $pagedSql).Replace('{Cols}', $cols)
})
    }
}