# Define variables
$directoryPath = "Fast.Shared/Database"
$modelsPath = "$directoryPath/Models"
$externalMethodsPath = "$directoryPath/ScaffoldMethods.ps1"
$fileFilter = "*.cs"
$oldTimestamp = Get-Date -Year 1980 -Month 1 -Day 1  # used to detect old files after scaffolding

# Load external methods
. "$externalMethodsPath"

# Set the last modified timestamp for all entity files to a single timestamp to easily detect old files after scaffolding
Set-LastModifiedTimestamp -directoryPath $modelsPath -fileFilter $fileFilter -targetTimestamp $oldTimestamp

# Scaffold the database context and entities
dotnet tool restore
if ($LASTEXITCODE -ne 0) { exit 1 }

# The donet EF scaffold generated files have custom modifications defined in the CodeTemplates folder
# They use the t4 templates to generate the files
# When you update EF Core versions, you may need to update the t4 templates as well by re-running the below commands:
#   cd Fast.Shared/Database
#   dotnet new install Microsoft.EntityFrameworkCore.Templates
#   dotnet new ef-templates
# The t4 template files are generated but they have custom modifications in DbContext.t4 and EntityType.t4
# Look for comments that say "Implefast modified by t4"
# install VSCode extension "zbecknell.t4-support" to enable t4 syntax highlighting
# EF Core tools automatically detect T4 templates if they are in the usual folder structure of the project directory

dotnet tool run dotnet-ef dbcontext scaffold `
  "Host=sql.implefast.com;Database=superior_test;Port=6432;Username=postgres;Password=28UTu6hn4q@z" `
  Npgsql.EntityFrameworkCore.PostgreSQL `
  --startup-project "Fast.Shared" `
  --project "Fast.Shared" `
  --namespace "Fast.Shared.Database.Models" `
  --context-namespace "Fast.Shared.Database" `
  --context "MyDbContext" `
  --context-dir "Database" `
  --output-dir Database/Models `
  --no-onconfiguring `
  --data-annotations `
  --force `
  --schema public

if ($LASTEXITCODE -ne 0) { exit 1 }

# Remove old entity files that were not updated after scaffolding
Remove-TimestampedFiles -directoryPath $modelsPath -fileFilter $fileFilter -targetTimestamp $oldTimestamp

# Normalize line endings to prevent Git from marking unchanged files as modified after scaffolding
Convert-LineEndings -directoryPath $directoryPath -fileFilter $fileFilter

# Output the current working directory
Write-Host (Get-Location).Path
